获取 foreach 循环中的下一个元素 [英] Get next element in foreach loop

查看:74
本文介绍了获取 foreach 循环中的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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;

这篇关于获取 foreach 循环中的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆