With functional programming all the rage, I feel I should be using PHP's array_*
functions more. But when I compare these two identical implementations, I can't help but think foreach
is more readable. Am I just being a dinosaur?
(The foreach
implementation takes 1/4 the time, but performance is not of interest for me here, now).
Which do you like better and why?
// Create $attendeeNames from $allPeople who are in the $selectedPeople array
foreach ($allPeople as $person) {
$id = $person['id'];
$name = $person['name'];
if (in_array($id, $selectedPeople)) {
$attendeeNames[] = $name;
}
}
// Same, but with array functions
$attendees = array_filter($allPeople,
function($item) use ($selectedPeople) {
$id = $item['id'];
return in_array($id, $selectedPeople);
});
$attendeeNames = array_map(
function($attendee) {
return $attendee['name'];
}, $attendees);