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

Sebastian Hoitz picture Sebastian Hoitz · Mar 15, 2011 · Viewed 29.8k times · Source

Is there an SPL Reverse array iterator in PHP? And if not, what would be the best way to achieve it?

I could simply do

$array = array_reverse($array);
foreach($array as $currentElement) {}

or

for($i = count($array) - 1; $i >= 0; $i--)
{

}

But is there a more elegant way?

Answer

linepogl picture linepogl · Sep 10, 2014

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.