在PHP Foreach中查找最后一个元素的下一个

时间:2015-08-03 20:38:07

标签: php arrays indexing foreach

我需要编写一个返回foreach循环中倒数第二个元素的脚本。像下面的概念。我该怎么做?

foreach($row as $r) {
    if (element index is last - 1) {
        echo "The next-to-last element is" . $r;
    }
}

2 个答案:

答案 0 :(得分:4)

这应该适合你:

只需将数组的键放入变量中,然后检查迭代的当前键是否等于倒数第二个键。

$keys = array_keys($row);
$penultimatekey = count($row)-2 >= 0 ? count($row)-2 : 0;

foreach($row as $k => $r) {
    if ($k == $keys[$penultimatekey]) {
        echo "The next-to-last element is" . $r;
    }
}

答案 1 :(得分:0)

将指针移动到末尾,然后将其倒回一个点。没有额外的循环或计算数组。

end($row);
prev($row);
echo "The next-to-last element is: " . current($row);
相关问题