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?
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With