Iterate in reverse through an array with PHP - SPL solution?

There is no ReverseArrayIterator to do that. You can do

$reverted = new ArrayIterator(array_reverse($data));

or make that into your own custom iterator, e.g.

class ReverseArrayIterator extends ArrayIterator 
{
    public function __construct(array $array)
    {
        parent::__construct(array_reverse($array));
    }
}

A slightly longer implementation that doesn't use array_reverse but iterates the array via the standard array functions would be

class ReverseArrayIterator implements Iterator
{
    private $array;

    public function __construct(array $array)
    {
        $this->array = $array;
    }

    public function current()
    {
        return current($this->array);
    }

    public function next()
    {
        return prev($this->array);
    }

    public function key()
    {
        return key($this->array);
    }

    public function valid()
    {
        return key($this->array) !== null;
    }

    public function rewind()
    {
        end($this->array);
    }
}

Here is a solution that does not copy and does not modify the array:

for (end($array); key($array)!==null; prev($array)){
  $currentElement = current($array);
  // ...
}

If you also want a reference to the current key:

for (end($array); ($currentKey=key($array))!==null; prev($array)){
  $currentElement = current($array);
  // ...
}

This works always as php array keys can never be null and is faster than any other answer given here.


$item=end($array);
do {
...
} while ($item=prev($array));