Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_reduce with initial parameter as an array

I have this initial array:

[
    0 => ['id' => 5, 'value' => 50],
    1 => ['id' => 6, 'value' => 60],
    2 => ['id' => 7, 'value' => 70],
]

and want to convert it to:

[
    5 => ['value' => 50],
    6 => ['value' => 60],
    7 => ['value' => 70],
]

At first, I tried to use map, but it can't modify the array keys, so I thought reduce would solve the problem because it reduces the array to a single value, in this case, an array. So I tried:

array_reduce(
    $array,
    function($carry, $item) {
        return $carry[$item['id']] = $item['value'];
    },
    []
);

But it returns this error Cannot use a scalar value as an array. What am I doing wrong? Does array_reduce cannot receive an array as an initial value?

like image 204
Mathius17 Avatar asked Mar 12 '23 09:03

Mathius17


1 Answers

Your array_reduce didn't work because You weren't returning the accumulator array (carry in Your case) from the callback function.

array_reduce(
    $array,
    function($carry, $item) {
        $carry[$item['id']] = $item['value'];
        return $carry; // this is the only line I added :)
    },
    []
);

I came to this question while looking for a way to use array_reduce, so I felt I should write this comment. I hope this will help future readers. :)

like image 98
Aleksandar Avatar answered Mar 15 '23 05:03

Aleksandar