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;
}
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.
You can build on your former success and use array_combine...
$get_user_id = function($user) {return $user->getId();};
$indexedUsers = array_combine(array_map($get_user_id, $users), $users);
First off, I doubt array_map()
is faster than your original foreach
loop. Never change code because you think it's faster. Of course, if you think it's more elegant and the speed difference is insignificant, then nobody should care.
You can often think of using iterators in these contexts:
class ArrayGetIdIterator extends ArrayIterator
{
public function key()
{
return $this->current()->getId();
}
}
$indexedUsers = iterator_to_array(new ArrayGetIdIterator($users));
To minimize boilerplate code and maximize reusability, the constructor could accept some type of arguments (e.g, which function to call) and you could create a static helper.
Although, personally, I would just take your original code, wrap it into a reusable function and call it a day.