views:

218

answers:

3

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?

+2  A: 

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);
}
Gumbo
The code looks pretty complicated, and it's prone to error (too many "nexts/prevs" and very strange things can happen...).
pako
+7  A: 

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() ); // null
var_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:Dog
Current: Dog - Next:Elephant
Current: Elephant - Next:Tiger
Current: Tiger - Next:Shark
Current: 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().

Gordon
+1 Didn't even know these ([x]Iterators) existed, very useful, espec the DirectoryIterator. That's going to save me a bulk load of work next time I'm doing file stuff. Thanks :)
Psytronic
@Psytronic they are really neat. The ability to stack them allows for very cool and flexible stuff. Unfortunately, there are poorly documented, but have a look at http://www.phpro.org/tutorials/Introduction-to-SPL.html
Gordon
Unfortunately, the solution doesn't work if the array contains objects and not strings. I get the following exception:`Catchable fatal error: Object of class MySampleClass could not be converted to string in /home/www/test.php on line 398`
pako
@pako Either implement the `__toString` method in `MySampleClass` or pass `CachingIterator::TOSTRING_USE_CURRENT` as the second param in the CachingIterator constructor.
Gordon
Okay I will try that. But why does the iterator need this step at all? I hope it doesn't change the order of the elements in the array based on their string representations.
pako
@pako I don't know why it needs this step, but apparently it does. The Iterators are unfortunately poorly documented at the moment. The solution I gave is based on using PHP's Reflection API and Trial and Error. If you are concerned the Iterator will do something it shouldn't do, make sure with a UnitTest.
Gordon
+2  A: 

Use array_keys.

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