我需要编写一个返回foreach循环中倒数第二个元素的脚本。像下面的概念。我该怎么做?
foreach($row as $r) {
if (element index is last - 1) {
echo "The next-to-last element is" . $r;
}
}
答案 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);