Search code examples
phpforeach

Get next element in foreach loop


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.


Solution

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