How to use a variable in the array_walk?

Asked

Viewed 117 times

5

I’m trying a solution without going through "manually"(foreach) an array, to add in the subarrays, a new pair of chave => valor. With the array_walk I can invoke a callback and treat the array but as 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 one Undefined variable whether declared and with an assigned value.

Using the key use in the role of callback, it does not add the new key:

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

1 answer

3


To documentation says that when using array_walk() only the values will be changed by default or 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 potentially be changed; its Structure cannot be Altered, i.e., the Programmer cannot add, unset or reorder Elements. If the callback does not respect this requirement, the behavior of this Function is Undefined, and unpredictable.

Due to this restriction, I believe it is more reliable to use array_map() that generates a similar, array_walk() changes the input array while array_map() not what he does is 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 array item that should be passed as reference and the second value ($token)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.