Home > OS >  PHP get 2 keys of an array in single iteration
PHP get 2 keys of an array in single iteration

Time:08-18

I have a foreach loop that is iterating over a nested array. When its iterating first time it gives me key and value, but i also need a key that is going to be in the following iteration (following key). In other words.. Each time the loop runs I need to get current key and also following key of an array if exists (2 keys of an array in single iteration). I have tried the following code but looks like it doesn't work. I would highly appreciate your help guys

foreach ($array as $foo => $bar) {

    var_dump($foo);
    next($array);
    var_dump($foo);
    die();
}

CodePudding user response:

Instead of using foreach, you can get the keys list and iterate over them:

$keys = array_keys($array);
for ($i = 0; $i < count($array); $i  ) {
    $value = $array[$keys[$i]];
    $nextKey = $keys[$i 1] ?? null;
    if ($nextKey !== null) {
    }
}

CodePudding user response:

Since foreach creates a copy of the array while iterating over it, making next calls will only affect the original array in-place. You can however use an iterator to visit the 2 indexes in every iteration like below using ArrayIterator.

Note that you will have to keep valid checks to make sure you aren't accessing an offset/key that doesn't exist.

Snippet:

<?php

$array = range(1, 19);

$it = (new ArrayObject( $array ))->getIterator();

while($it->valid()){
  
  for($i = 0; $i < 2 && $it->valid();   $i, $it->next()){
    echo $it->key(), " ";
  }
  
  echo PHP_EOL;
}

Online Demo


Note: You can also create custom iterators for better syntactic sugar if you like.

  • Related