Good afternoon, I encountered such a problem. There is an associative array.

For example.

$foo = array('x'=>'x_val','y'=>'y_val','z'=>'z_val'); 

And there is a foreach .

 foreach ($foo as $key=>$val){ //Тут какая то логика } 

We need to take the next $ val in the current iteration. Well or $key .

How can this be achieved?

  • one
    and at the last iteration? He you always need or only under some conditions? - splash58
  • @ splash58 is not needed on the last one. You can say if the condition is not the last one, then take the latter if you can return 0 or null . - Raz Galstyan
  • 2
    for example, the sync index $i=0; before loop and print_r(array_slice($foo, ++$i, 1)); - splash58

3 answers 3

the easiest way is to use an auxiliary array of matches

 $foo = array('x'=>'x_val', 'y'=>'y_val', 'z'=>'z_val'); $keys = array_keys($foo); array_shift($keys); $matches = array_combine(array_keys($foo), $keys + [-1 => null]); foreach($foo as $k => $v){ $nextKey = $matches[$k]; print_r([$k, $nextKey]); } 

result

 Array( [x] => y [y] => z [z] => ) 

However, it is generally worth considering that there is a key order in the associative array, and whether it generally makes sense and is it guaranteed when traversing

  • Thanks for the decision, helped - Raz Galstyan
  • Who is the answer minusovat? - Raz Galstyan

Through array_keys and array_search, but I would not say that this is the best way (there is a better way in the comments)

 $tmp = array_keys($foo); // ["1" => "x", "2" => "y" ...] foreach ($foo as $key=>$val){ $tmp_key = array_search($key, $tmp); // узнаем ключ $tmp по которому хранится значение $key $nextKey = $tmp[$tmp_key + 1]; // следующий ключ $nextValue = $foo[$nextKey]; // следующее значение echo $nextValue; } 

    Use next

     $array = ['x' => 1, 'y' => 2, 'z' => 3]; foreach ($array as $key => $value) { $nextValue = next($array); // Что бы узнать ключ следующего значения, можно вызвать key($array); echo $value . ' ' . $nextValue . PHP_EOL; } /* Вывод: 1 2 2 3 3 */ 

    UPD: in the comments suggested that this example only works in PHP 7

    UPD2: Here is a version that works the same in PHP 5 and PHP 7

     $array = ['x' => 1, 'y' => 2, 'z' => 3]; while ($key = key($array) !== null) { $value = current($array); $nextValue = next($array); echo $value . ' ' . $nextValue . PHP_EOL; } /* Вывод: 1 2 2 3 3 */ 
    • eval.in/946801 - splash58
    • @ splash58 PHP 7 works as expected eval.in/946805 - ilyaplot
    • this is the way it displays the values, not the keys - teran
    • but there or there, yes. - teran
    • one
      in php 7 foreach does not move the pointer of the current element, so this code will depend on the version of php - teran