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

后端 未结 11 1993
清酒与你
清酒与你 2020-12-05 13:51

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)         


        
11条回答
  •  悲&欢浪女
    2020-12-05 14:28

    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.

提交回复
热议问题