Get next element in foreach loop

前端 未结 9 552
猫巷女王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:22

    You could get the keys/values and index

    '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 = ( => )
    

提交回复
热议问题