【发布时间】:2015-10-26 02:16:48
【问题描述】:
我需要编写一个脚本,在 foreach 循环中返回倒数第二个元素。类似于下面的概念。我该怎么做呢?
foreach($row as $r) {
if (element index is last - 1) {
echo "The next-to-last element is" . $r;
}
}
【问题讨论】:
标签: php arrays indexing foreach
我需要编写一个脚本,在 foreach 循环中返回倒数第二个元素。类似于下面的概念。我该怎么做呢?
foreach($row as $r) {
if (element index is last - 1) {
echo "The next-to-last element is" . $r;
}
}
【问题讨论】:
标签: php arrays indexing foreach
这应该适合你:
只需将数组的键放入变量中,然后检查迭代的当前键是否等于倒数第二个键。
$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;
}
}
【讨论】:
count($row)-2 部分移到 foreach 之前的变量中,这样您就不会每次都进行该计算,也不会使用两次。
$keys = array_keys($row); $nextToLast = $keys[count($keys)-2]; foreach($row as $k => $r) { if ($k === nextToLast) { echo "The next-to-last element is" . $r; } }
将指针移到末尾,然后将其倒回一个点。没有额外的循环或计算数组。
end($row);
prev($row);
echo "The next-to-last element is: " . current($row);
【讨论】: