while(list($key, $value) = each($array)) vs. foreach($array as $key => $value)?

tomsseisums picture tomsseisums · Jul 22, 2010 · Viewed 66k times · Source

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?

Answer

John Kugelman picture John Kugelman · Jul 22, 2010

Had you previously traversed the array? each() remembers its position in the array, so if you don't reset() it you can miss items.

reset($array);
while(list($key, $value) = each($array))

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.

array each ( array &$array )

Return the current key and value pair from an array and advance the array cursor.

After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

(Source: PHP Manual)