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

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

    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.

提交回复
热议问题