Recently I experienced this weird problem:
while(list($key, $value) = each($array))
was not listing all array values, where replacing it with...
foreach($array as $key => $value)
...worked perfectly.
And, I'm curious now.. what is the difference between those two?
Well, one difference is that
each()
will only work on arrays (well only work right).foreach
will work on any object that implements thetraversable
interface (Which of course includes the built in array type).There may be a micro-optimization in the foreach. Basically, foreach is equivilant to the following:
Whereas
each
basically does the following:So three lines are the same for both. They are both very similar. There may be some micro-optimizations in that
each
doesn't need to worry about thetraversable
interface... But that's going to be minor at best. But it's also going to be offset by doing the boolean cast and check in php code vsforeach
's compiled C... Not to mention that in yourwhile/each
code, you're calling two language constructs and one function, whereas withforeach
it's a single language construct...Not to mention that
foreach
is MUCH more readable IMHO... So easier to read, and more flexible means that -to me-foreach
is the clear winner. (that's not to say thateach
doesn't have its uses, but personally I've never needed it)...Warning! Foreach creates a copy of the array so you cannot modify it while foreach is iterating over it.
each()
still has a purpose and can be very useful if you are doing live edits to an array while looping over it's elements and indexes.Both
foreach
andwhile
will finish their loops and the array "$array
" will be changed. However, the foreach loop didn't change while it was looping - so it still iterated over every element even though we had deleted them.Update: This answer is not a mistake.
I thought this answer was pretty straight forward but it appears the majority of users here aren't able to appreciate the specific details I mention here.
Developers that have built applications using libdom (like removing elements) or other intensive map/list/dict filtering can attest to the importance of what I said here.
If you do not understand this answer it will bite you some day.
Had you previously traversed the array?
each()
remembers its position in the array, so if you don'treset()
it you can miss items.For what it's worth this method of array traversal is ancient and has been superseded by the more idiomatic foreach. I wouldn't use it unless you specifically want to take advantage of its one-item-at-a-time nature.
(Source: PHP Manual)
If you passed
each
an object to iterate over, the PHP manual warns that it may have unexpected results.What exactly is in
$array