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

后端 未结 11 1862
清酒与你
清酒与你 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:36

    $array1= array(10,20,30,40,50);

            for($i = count($array1) - 1; $i >= 0; $i--)
            {
                $array2[]  = $array1[$i];
    
            }
    
            echo "<pre>";
                print_r($array2);
            echo "</pre>";
    
    0 讨论(0)
  • 2020-12-05 14:40
    $item=end($array);
    do {
    ...
    } while ($item=prev($array));
    
    0 讨论(0)
  • 2020-12-05 14:41

    Note that if you want to preserve the keys of the array, you must pass true as the second parameter to array_reverse:

    $array = array_reverse($array, true);
    foreach ($array as $currentElement) {
        // do something here
    }
    
    0 讨论(0)
  • 2020-12-05 14:44

    This could be a more performant way since it doesnt construct a new array. It also handles empty arrays well.

    $item = end($items);
    while($item)
    {
        ...do stuff...
        $item = prev($items);
    }
    
    0 讨论(0)
  • 2020-12-05 14:47
    $array = array_reverse($array);
    foreach($array as $key => $currentElement) {}
    

    This is better way to use. It will take care of keys also, if they are not sequential or integer.

    0 讨论(0)
提交回复
热议问题