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

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

问题描述

我有一个foreach循环,我想看看循环中是否有下一个元素,这样我可以比较当前元素和下一个元素。我怎样才能做到这一点?我已经读过关于当前和下一个功能,但我不知道如何使用它们。

在此先感谢

独特的方法是将数组和然后是循环。这也适用于非数字索引数组:

  $ items = array(
'one'=> ;'two',
'two'=>'two',
'three'=>'three'
);
$ backwards = array_reverse($ items);
$ last_item = NULL; ($ last_item === $ current_item){
//他们匹配
}
foreach($ backwards as $ current_item) last_item = $ current_item;



$ b

如果您仍然对使用 current 下一个函数,您可以这样做:

  $ items = array('two','two','three'); 
$ length = count($ items);
($ i = 0; $ i <$ length - 1; ++ $ i){
if(current($ items)=== next($ items)){
/他们匹配


$ / code $ / pre

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


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.

Thanks in advance

解决方案

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;
}

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 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天全站免登陆