Search code examples
phparraysphp-5.3

Function similar to array_map to re-index an array


I've recently been using array_map to replace this kind of code:

$users = ...;
$usersIds = array();
foreach ($users as $user) {
   $usersIds[] = $user->getId();
}

with

$users = ...;
$usersIds = array_map(function ($user) {
    return $user->getId();
}, $users);

It's more elegant, and i guess that this more efficient.

Now i'd like to know if the following code could be improved with a function similar to array_map:

$users = ...;
$indexedUsers = array();
foreach ($users as $user) {
    $indexedUsers[$user->getId()] = $user;
}

Solution

  • As you already have the keys, just combine it:

    $indexedUsers = array_combine($usersIds, $users);
    

    Apart from that, foreach normally is elegant, especially these trivial cases you outline don't need much function logic, so I'd prefer the iterator pattern here instead of going functional.