1

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!

7
  • 3
    Have you read the documentation of array_walk()? It explains in the first screen how to achieve what you want. Commented May 29, 2020 at 12:29
  • += is for numbers. Read about creating/modifying array elements with square bracket syntax Commented May 29, 2020 at 12:31
  • 1
    I did not say it cannot be done with +=. It is more natural to use []=. Commented May 29, 2020 at 12:36
  • 2
    Yes, I agree with @axiac. To add items via key-value to an array, I recommend you using the standard way: array[key]=value. Or without a defined key list[]=value. Commented May 29, 2020 at 12:57
  • 1
    @axiac Ok, thanks. I will take note of that! Commented May 29, 2020 at 12:59

1 Answer 1

4

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

array_walk($array, function(array &$item): void {
    $item['locked'] = 0;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.