SpangNation

How To Specify Keys When Mapping A Collection

June 13, 2017

If you’ve ever needed to alter a collection, and map a specific key to a specific value, here is how you go about it.

Let’s say we’ve got a collection of employees:

$employees = [
    [
        'name' => 'Ivan',
        'department' => 'Intern',
        'email' => 'IvanTheInternable@email.com'
    ],
    [
        'name' => 'Roger',
        'department' => 'We aren’t quite sure...',
        'email' => 'roger@email.com'
    ],
    [
        'name' => 'Dave',
        'department' => 'IT',
        'email' => 'dave@email.com'
    ],
];

And let’s say we need to return an associative array with the employee’s email address mapped to their name.

Here’s how you go about accomplishing that using Laravel’s reduce method.

$emailLookup = $employees->reduce(function ($emailLookup, $employee) {
    $emailLookup[$employee['email']] = $employee['name'];
    return $emailLookup;
}, []);

If we die and dump our $emailLookup variable, this is what we’ll get:

array:3 [
  "IvanTheInternable@email.com" => "Ivan"
  "roger@email.com" => "Roger"
  "dave@email.com" => "Dave"
]

That’s it! Pretty simple stuff.

I found this answer on Adam Wathan’s site, and he has a video explanation if you’d like more information. I think it’s part of his Refactoring to Collections book. It’s a great book/course. I highly recommend it.