Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next element in foreach loop

Tags:

foreach

php

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

like image 958
chchrist Avatar asked Feb 23 '11 20:02

chchrist


People also ask

Can I get index in forEach JavaScript?

Get The Current Array Index in JavaScript forEach()forEach(function callback(v) { console. log(v); }); The first parameter to the callback is the array value. The 2nd parameter is the array index.

How to break out of a forEach loop c#?

At any point within the body of an iteration statement, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement.

Does array have next?

The hasNext() method returns true if there are more elements in the ArrayList and otherwise returns false. The next() method returns the next element in the ArrayList.

What is forEach in c#?

The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.


2 Answers

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;

like image 160
Stephen Avatar answered Sep 23 '22 04:09

Stephen


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     } } 
like image 27
pronskiy Avatar answered Sep 23 '22 04:09

pronskiy