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)
Based on linepogl's answer, I came up with this function:
/**
* Iterate an array or other foreach-able without making a copy of it.
*
* @param array|\Traversable $iterable
* @return Generator
*/
function iter_reverse($iterable) {
for (end($iterable); ($key=key($iterable))!==null; prev($iterable)){
yield $key => current($iterable);
}
}
Usage:
foreach(iter_reverse($my_array) as $key => $value) {
// ... do things ...
}
This works on arrays and other iterables without first making a copy of it.