Laravel collections mapWithKeys
Asked Answered
Z

1

8

I have been trying to create an array using laravel's collection function called mapWithKeys, but I couldn't achieve what I need.

Here is my code,

$years = range(1900, date('Y'));

return collect($years)->mapWithKeys(function($value){
    return [$value => $value];
})->all();

Expected result

Array
(
    [1900] => 1900
    [1901] => 1901
    [1902] => 1902
    ....
    [2017] => 2017
)

But what I get is

Array
(
    [0] => 1900
    [1] => 1901
    [2] => 1902
    ...
    [117] => 2017
)
Zanazander answered 1/2, 2017 at 12:37 Comment(0)
J
4

I've tested this code and it works perfectly:

$years = range(1900, date('Y'));
return collect($years)->map(function($i) {
    return ['year' => $i];
}, $years)->pluck('year', 'year');
Junto answered 1/2, 2017 at 12:43 Comment(3)
Array ( [0] => Array ( [1900] => 1900 ) ) I'm getting values like this.Zanazander
Thanks. It works. But I'm wondering why it is not working with mapWithKeys function. If I replace [$value => $value] to something like ['s'.$value => $value] it works. I think the problem is with key and value being same.Zanazander
@SaravananSampathkumar under the hood mapWithKeys() uses array_map(), so it's just rebuilds given array. So you can't use this helper for building a plain array with desired structure.Junto

© 2022 - 2024 — McMap. All rights reserved.