Is it possible to “peek ahead” while iterating an array in PHP 5.2? For example, I often use foreach to manipulate data from an array:
foreach($array as $object) {
// do something
}
But I often need to peek at the next element while going through the array. I know I could use a for loop and reference the next item by it’s index ($array[$i+1]), but it wouldn’t work for associative arrays. Is there any elegant solution for my problem, perhaps involving SPL?
You can use the CachingIterator for this purpose.
Here is an example:
The CachingIterator is always one step behind the inner iterator:
Thus, when you do
foreachover$collection, the current element of the inner ArrayIterator will be the next element already, allowing you to peek into it:Will output:
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_CURRENTas 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_CACHEand then you can fetch the cached results withgetCache().