Get next element in foreach loop

前端 未结 9 519
猫巷女王i
猫巷女王i 2020-11-30 03:56

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 cu

相关标签:
9条回答
  • 2020-11-30 04:19

    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
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:21

    You could get the keys of the array before the foreach, then use a counter to check the next element, something like:

    //$arr is the array you wish to cycle through
    $keys = array_keys($arr);
    $num_keys = count($keys);
    $i = 1;
    foreach ($arr as $a)
    {
        if ($i < $num_keys && $arr[$keys[$i]] == $a)
        {
            // we have a match
        }
        $i++;
    }
    

    This will work for both simple arrays, such as array(1,2,3), and keyed arrays such as array('first'=>1, 'second'=>2, 'thrid'=>3).

    0 讨论(0)
  • 2020-11-30 04:22

    You could get the keys/values and index

    <?php
    $a = array(
        'key1'=>'value1', 
        'key2'=>'value2', 
        'key3'=>'value3', 
        'key4'=>'value4', 
        'key5'=>'value5'
    );
    
    $keys = array_keys($a);
    foreach(array_keys($keys) as $index ){       
        $current_key = current($keys); // or $current_key = $keys[$index];
        $current_value = $a[$current_key]; // or $current_value = $a[$keys[$index]];
    
        $next_key = next($keys); 
        $next_value = $a[$next_key] ?? null; // for php version >= 7.0
    
        echo  "{$index}: current = ({$current_key} => {$current_value}); next = ({$next_key} => {$next_value})\n";
    }
    

    result:

    0: current = (key1 => value1); next = (key2 => value2) 
    1: current = (key2 => value2); next = (key3 => value3) 
    2: current = (key3 => value3); next = (key4 => value4) 
    3: current = (key4 => value4); next = (key5 => value5) 
    4: current = (key5 => value5); next = ( => )
    
    0 讨论(0)
提交回复
热议问题