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:
Apart from that,
foreachnormally 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.