Peek ahead when iterating an array in PHP Peek ahead when iterating an array in PHP arrays arrays

Peek ahead when iterating an array in PHP


You can use the CachingIterator for this purpose.

Here is an example:

$collection = new CachingIterator(                  new ArrayIterator(                      array('Cat', 'Dog', 'Elephant', 'Tiger', 'Shark')));

The CachingIterator is always one step behind the inner iterator:

var_dump( $collection->current() ); // nullvar_dump( $collection->getInnerIterator()->current() ); // Cat

Thus, when you do foreach over $collection, the current element of the inner ArrayIterator will be the next element already, allowing you to peek into it:

foreach($collection as $animal) {     echo "Current: $animal";     if($collection->hasNext()) {         echo " - Next:" . $collection->getInnerIterator()->current();     }     echo PHP_EOL; }

Will output:

Current: Cat - Next:DogCurrent: Dog - Next:ElephantCurrent: Elephant - Next:TigerCurrent: Tiger - Next:SharkCurrent: Shark

For some reason I cannot explain, the CachingIterator will always try to convert the current element to string. If you want to iterate over an object collection and need to access properties an methods, pass CachingIterator::TOSTRING_USE_CURRENT as the second param to the constructor.


On a sidenote, the CachingIterator gets it's name from the ability to cache all the results it has iterated over so far. For this to work, you have to instantiate it with CachingIterator::FULL_CACHE and then you can fetch the cached results with getCache().


Use array_keys.

$keys = array_keys($array);for ($i = 0; $i < count($keys); $i++) {    $cur = $array[$keys[$i]];    $next = $array[$keys[$i+1]];}


You can use next and prev to iterate an array. current returns the current items value and key the current key.

So you could do something like this:

while (key($array) !== null) {    next($array);    if (key($array) === null) {        // end of array    } else {        $nextItem = value($array);    }    prev($array);    // …    next($array);}