23
Apr '14

PHP’s callback functions are known as being ‘dark magic’ but there are two array functions, namely array_map and array_filter which can be incredibly useful (and not that scary).

array_map gives you a very simple way of calling a function on each element of an array and returning the result in another array. I make great use of it when working with ORM models as it is perfect for extracting an array of IDs, names, email addresses or whatever from a model array.
As an example let’s imagine I have an array of User objects which have ‘name’ fields that I want to extract. I can simply do the following:

$names = array_map(function($user) { return $user->name; }, $users);

Ain’t that simple?

array_filter works in a very similar way but is used to run some logic against each element in an array, in order to decide whether that element is returned as part of the output array.
So if my User objects also had an ‘age’ field and I wanted to extract all users who are 18 years old or more I could do this:

$adults = array_filter($users, function($user) { return ($user->age >= 18); });

Now any readers paying attention will notice that in the above functions the parameters are swapped round i.e. array_map has the callback first and the array second and array_filter is vice-versa. It looks unpleasant but there is a degree of logic to this as array_map will accept multiple arrays as arguments, and array_filter doesn’t require the callback to be provided at all (in that situation all elements that evaluate as false would be removed).
Having said that PHP is famous for its inconsistent ordering of parameters in its core functions and it remains my biggest gripe with the language, just very slightly in front of most of its methods being in the root namespace. But hey, you can’t have everything right?