且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP:如何跳过foreach循环中的最后一个元素

更新时间:2022-02-15 02:45:50

使用变量来跟踪到目前为止已迭代了多少个元素,并在到达末尾时切断循环:

Use a variable to track how many elements have been iterated so far and cut the loop when it reaches the end:

$count = count($array);

foreach ($array as $key => $val) {
    if (--$count <= 0) {
        break;
    }

    echo "$key = $val\n";
}

如果您不关心内存,可以遍历缩短的数组副本:

If you don't care about memory, you can iterate over a shortened copy of the array:

foreach (array_slice($array, 0, count($array) - 1) as $key => $val) {
    echo "$key = $val\n";
}