Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 793
Sebastian Hoitz Avatar asked Mar 15 '11 17:03

Sebastian Hoitz


People also ask

How do I reverse an array in PHP?

PHP: array_reverse() function The array_reverse() function is used to reverse the order of the elements in an array. Specifies the name of the array. Specify TRUE or FALSE whether function shall preserve the array's keys or not. The default value is FALSE.

Which function is used to get an array in reverse order in PHP?

The array_reverse() function returns an array in the reverse order.

What is the method to reverse an array?

Array.prototype.reverse() The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.


2 Answers

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.

like image 97
linepogl Avatar answered Oct 26 '22 17:10

linepogl


$item=end($array); do { ... } while ($item=prev($array)); 
like image 33
AbiusX Avatar answered Oct 26 '22 16:10

AbiusX