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?
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.
The array_reverse() function returns an array in the reverse order.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With