Looping into arrays
optimization, Web Development, PHP March 19th, 2008
There are some sites that try to do a benchmark over FOREACH and the FOR statement and not always they give a good position about it.
To understand which one will be the faster one, is simple:
FOREACH will automatically points the array pointer to the beginning of the array and will create a copy of the array to perform the loop and will increment the pointer in one always. FOR does not, but the FOR statement will check the 3 conditions that you have used on it.
Looping into arrays you have 3 conditions with the FOR statement.
- Where the pointer starts.
- Until when you want to perform the loop.
- and how the pointer will be incremented.
Considering that you have 3 scalar conditions, the FOR statement will be much faster than the FOREACH statement.
Ex.
$array = explode(’ ‘,’ Consider the following examples. All of them display the numbers 1 through 10:’);
foreach($array as $key => $value) {
if($key > 0) {
echo ‘ ‘;
}
echo $value;
}
$size = sizeof($array);
for($key = 0; $key < $size; ++$key) {
if($key > 0) {
echo ‘ ‘;
}
echo $array[$key];
}
Posts
Leave a Comment
You must be logged in to post a comment.