Search code examples
phplaravellaravel-5laravel-5.3laravel-collection

Laravel collections mapWithKeys


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
)

Solution

  • 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');