Hướng dẫn foreach php next element

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.

Nội dung chính

  • How to get next array element in PHP?
  • Can I use continue in foreach PHP?
  • How to go to next iteration in for loop PHP?
  • How do you find the next value in an array?

Thanks in advance

asked Feb 23, 2011 at 20:38

1

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;

answered Feb 23, 2011 at 20:43

StephenStephen

18.6k9 gold badges59 silver badges98 bronze badges

0

You could probably use while loop instead of foreach:

while [$current = current[$array] ]
{
    $next = next[$array];
    if [false !== $next && $next == $current]
    {
        //do something with $current
    }
}

Lucas

16.5k30 gold badges105 silver badges173 bronze badges

answered Oct 21, 2011 at 13:16

pronskiypronskiy

1,3391 gold badge11 silver badges8 bronze badges

1

As php.net/foreach points out:

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

In other words - it's not a very good idea to do what you're asking to do. Perhaps it would be a good idea to talk with someone about why you're trying to do this, see if there's a better solution? Feel free to ask us in ##PHP on irc.freenode.net if you don't have any other resources available.

answered Feb 24, 2011 at 8:05

TMLTML

12.5k3 gold badges36 silver badges44 bronze badges

If the indexes are continuous:

foreach [$arr as $key => $val] {
   if [isset[$arr[$key+1]]] {
      echo $arr[$key+1]; // next element
   } else {
     // end of array reached
   }
}

Tim

2,4461 gold badge23 silver badges30 bronze badges

answered Feb 23, 2011 at 20:42

Mārtiņš BriedisMārtiņš Briedis

17.1k5 gold badges53 silver badges74 bronze badges

2

You could get the keys/values and index

Chủ Đề