DEV Community

Anders Björkland
Anders Björkland

Posted on

I just Callback to say: filter and map in PHP 🎶

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 to array_map and array_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)
}
*/
Enter fullscreen mode Exit fullscreen mode

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)
}
*/
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

What about you?

Comment below and let us know what you think ✍

Further Reading

Top comments (3)

Collapse
 
dawiddahl profile image
Dawid Dahl

The fact that the argument order is different between map and filter is what I dislike the most about PHP. 😆

Collapse
 
andersbjorkland profile image
Anders Björkland

There's even a library out there just to make php functions take arguments in a consistent order! 😁
I haven't reached for that though. Intelliphense for VSCode is pretty good at reminding me which is which!

Collapse
 
dawiddahl profile image
Dawid Dahl

Hah, seriously? I’ll try to find it, thanks and see you soon! 🙏🏻🙂