如何设置foreach循环从最后一个数组开始?

3

我该如何设置我的foreach循环来从数组的最后一个条目开始查找,然后每个循环都向后而不是向前进行?

谢谢。


这是 https://dev59.com/im435IYBdhLWcg3wnBZ8 的副本。 - Alex
3个回答

10

你可以通过 反转 数组来实现:

$reverse = array_reverse($array, true); // true to preserve keys
foreach($reverse as $key => $value) { /* etc. */ }

如果您确定数组仅包含数字键,那么这可能更快:

for($i = count($array) - 1; $i >= 0; $i--) {
  /* etc. */
}

1
foreach(array_reverse($array, true) as $key=>$value)

array_reverse函数将反转一个数组。


1
你可以这样做:
$values = array();
$max = count($values);

foreach($i = $max; $i > 0; $i--) {
    $key = $values[$i];
    // do something with the key
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接