I just Callback to say: filter and map in PHP 🎶
Anders Björkland
Posted on December 16, 2021
Just the Gist
Yesterday the ghost of the present showed us some actual nice features. One of these were the first class function and how we could both assign functions to variables and also pass functions as arguments to other functions. Today we will see the latter in action when we pass some functions toarray_map
andarray_filter
. The function will be used as a callback to apply to each element of the array.
Let's say we want to square all the numbers in an array. We can have a square function do this, by passing it into the array_map
function. Let's have a look 👇
<?php
$numbers = range(0, 5);
$square = function($n) {
return $n * $n;
};
$squaredNumbers = array_map($square, $numbers);
var_dump($squaredNumbers);
/* Output:
array(6) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(4)
[3]=>
int(9)
[4]=>
int(16)
[5]=>
int(25)
}
*/
Now we can use the array_filter
function to just get the even numbers. Here's how we can do that:
// ...the previous code as seen above. We have $squaredNumbers with same values.
$isEven = function($n) {
return $n % 2 == 0;
};
$evenSquaredNumbers = array_filter($squaredNumbers, $isEven);
var_dump($evenSquaredNumbers);
/* Output:
array(3) {
[0]=>
int(0)
[2]=>
int(4)
[4]=>
int(16)
}
*/
array_filter
has successfully filtered out all the odd numbers. We are left with 3 elements in the array, however, you can see that it has preserved the respective indexes. In some cases, this may be what you want. But if we were to use a regular for-loop we might not get the result we are expecting. If we don't want the indexes preserved we can wrap the array_filter
function in a array_values
function, like this:
$evenSquaredNumbers = array_values(array_filter($squaredNumbers, $isEven));
What about you?
Comment below and let us know what you think ✍
Further Reading
- First-class function on Wikipedia: https://en.wikipedia.org/wiki/First-class_function
- Callback on Wikipedia: https://en.wikipedia.org/wiki/Callback_(computer_programming)
- I Just Called to say I Love You - Steview Wonder: https://www.youtube.com/watch?v=wyXNQiRCfRg
Posted on December 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.