1

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!

M Reza Saberi
  • 7,134
  • 9
  • 47
  • 76

1 Answers1

6

$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.

rickdenhaan
  • 10,857
  • 28
  • 37