Possible Duplicate:
for vs foreach vs while which is faster for iterating through arrays in php
For each
and while
, which of these is faster, recommended, and what are their resource usages like?
Possible Duplicate:
for vs foreach vs while which is faster for iterating through arrays in php
For each
and while
, which of these is faster, recommended, and what are their resource usages like?
foreach
is optimized for iteration over collections. That's a fancy way of saying that it works best (and fastest) when you use it with arrays (and as of PHP5, objects). You can use while()
to get the same effect as a foreach, but its not as efficient since you need to call list()
inside the while
loop.
foreach($array as $key => $value)
written with a while
is while(list($key,$value) = each($array))
. You can see the number of extra calls that are needed.
i think they should have the same speed. i prefer foreach because its safer.
That may depend on how you use them exactly. You can choose to pass an array by reference to the foreach
loop. In that case there will not be made a copy of the entire array. Optimizations like this probably have more effect than choosing between foreach
and while
.