获取 foreach 循环中的下一个元素

2021-12-26 00:00:00 foreach php

我有一个 foreach 循环,我想查看循环中是否有下一个元素,以便我可以将当​​前元素与下一个元素进行比较.我怎样才能做到这一点?我已经阅读了 current 和 next 函数,但我不知道如何使用它们.

I have a foreach loop and I want to see if there is a next element in the loop so I can compare the current element with the next. How can I do this? I've read about the current and next functions but I can't figure out how to use them.

提前致谢

推荐答案

一种独特的方法是反转数组和 then 循环.这也适用于非数字索引数组:

A unique approach would be to reverse the array and then loop. This will work for non-numerically indexed arrays as well:

$items = array(
    'one'   => 'two',
    'two'   => 'two',
    'three' => 'three'
);
$backwards = array_reverse($items);
$last_item = NULL;

foreach ($backwards as $current_item) {
    if ($last_item === $current_item) {
        // they match
    }
    $last_item = $current_item;
}

如果您仍然对使用 currentnext 函数感兴趣,您可以这样做:

If you are still interested in using the current and next functions, you could do this:

$items = array('two', 'two', 'three');
$length = count($items);
for($i = 0; $i < $length - 1; ++$i) {
    if (current($items) === next($items)) {
        // they match
    }
}

#2 可能是最好的解决方案.注意,$i <$length - 1; 将在比较数组中的最后两项后停止循环.我把它放在循环中,以便在示例中明确.你应该只计算 $length = count($items) - 1;

#2 is probably the best solution. Note, $i < $length - 1; will stop the loop after comparing the last two items in the array. I put this in the loop to be explicit with the example. You should probably just calculate $length = count($items) - 1;

相关文章