How to use a variable in array_walk?

5

I am trying a solution without going through "manually" ( foreach ) an array, to add in the subarrays, a new pair of chave => valor . With array_walk I can invoke a callback and treat the array but how do I pass a variable to its callback?

The array has the following structure:

$array = [
    [
        'id' => 1,
        'name' => 'abc'
    ],
    [
        'id' => 2,
        'name' => 'def'
    ]
];

I tried to add the new pairs as follows:

array_walk($array, function ($v, $k) { $v['token'] = $token; });

But I get a% w / w of% even with it declared and assigned value.

Using the key Undefined variable in the use function, it does not add the new key:

function ($v, $k) use ($token) { $v['token'] = $token; }
    
asked by anonymous 12.09.2016 / 18:54

1 answer

3

The documentation says that when using array_walk() only the values will be changed by default ie the structure will not be changed. When callback does not respect this rule the behavior of the function may be undefined or unpredictable.

  

Only the values of the array may be changed; its structure can not be altered, i.e., the programmer can not add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

Because of this constraint, I believe it is more reliable to use array_map() that generates a similarity, array_walk() changes the array of arrays while array_map() not what it does is to return a new one with the changes. >

$arr = array_map(function($item) use ($token){$item['novo'] = $token;  return $item; } , $array);

With array_walk() you can pass two arguments in the anonymous function, the first the current item of the array that should be passed as a reference and the second the value ( $token )

$token = 2015;
array_walk($array, function(&$item) use ($token){ $item['novo'] = $token; });
    
12.09.2016 / 19:11