each

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

Description

arrayeach
( 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.

Parameters

array

The input array.

Return Values

Returns the current key and value pair from the array
array. This pair is returned in a four-element
array, with the keys 0, 1,
key, and value. Elements
0 and key contain the key name of
the array element, and 1 and value
contain the data.

If the internal pointer for the array points past the end of the
array contents, each() returns
FALSE.

User Contributed Notes 17 notes

Regarding speed of foreach vs while(list) =eachI wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

Remember to use "reset()" if you iterate over an array with "each()" more than once! Example:

while(list($key,$value) = each($array)){
// code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block. You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.