Search code examples
phparray-walk

increment an integer in a array_walk() in PHP


I need to use an incremented value for the index orders2 of the array and I have tried the following:

$i = 0;
array_walk($arr1, function(&$a) {
  $i++;
  $a['orders2'] = $i;
});

Which says $i is unknown in the line $i++;.

I know I can use foreach() but I want to know if array_walk() has the bahavior of a regular loop. Any comments would be appreciated!


Solution

  • $i is not inside the scope of your anonymous function. You'll have to tell the function to import it:

    $i = 0;
    array_walk($arr1, function(&$a) use (&$i) {
      $i++;
      $a['orders2'] = $i;
    });
    

    You'll need to import it as a reference, because otherwise it will create a copy of $i instead of modifying the outer variable.