Skip to content
Advertisement

array_walk not working as expected when modifying the values

I am trying to add a new value to the array (I know it is possible with array_map() but I would like to test it with the array_walk()).

This is the code:

$array = [
    [
        'id'   => 1,
        'name' => 'Jesus',
    ],
    [
        'id'   => 2,
        'name' => 'David',
    ],
];

And I want this output:

$array = [
    [
        'id'     => 1,
        'name'   => 'Jesus',
        'locked' => 0,
    ],
    [
        'id'     => 2,
        'name'   => 'David',
        'locked' => 0,
    ],
];

I tried with the following code:

array_walk($array, static function(array $item): array {
    $item += ['locked' => 0];
    //var_dump($item); // Here the array has the three values.
    return $item;
});

// Also I tried the same code but not returning the array, I mean:

array_walk($array, static function(array $item): void {
    $item += ['locked' => 0];
    //var_dump($item); // Here the array has the three values.
});

Is it possible what I want with an array_walk()?


That would be the solution with an array_map().

$arrayMapped = array_map(static function(array $item): array {
    return $item += ['locked' => 0];
}, $array);

var_dump($arrayMapped);

Cheers!

Advertisement

Answer

Arrays are passed by value. You need to define the argument by reference using &

array_walk($array, function(array &$item): void {
    $item['locked'] = 0;
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement