A Comprehensive Guide to PHP array_filter Function

Summary: this tutorial shows you how to use the PHP array_filter function to filter elements of an array using a callback.

Introduction to PHP array_filter function

When you want to filter elements of an array, you often iterate over the elements and check whether each element should be included in the result array, for example:

By using the array_filter function, the code will be as expressive as follows:

The array_filter function allows you to filter elements of an array using a callback function.

The array_filter function iterates over the elements in the $items array and passes each element to the $callback function. If the callback function returns true, the element is included in the result array.

Note that the keys of the array are preserved.

PHP array_filter examples

Basic array_filter example

To filter out all odd numbers in the $items array, you use the array_filter function as follows:

Using callback as a method of a class

If the callback function is a method of a class, you can pass it to the array_filter function as follows:

See the following example.

The Odd class has a method isOdd() that returns true if the argument is an odd number, otherwise, it returns false.

To use the isOdd() method as the callback of the array_filter function, you use the following form:

In case the callback is a static method, you pass it to the array_filter as follows:

For example:

The Even class has a static method isEven that returns true if the argument is even, otherwise, it returns false.

To use the isEven method as the callback of the array_fitler you use:

Since PHP 5.3, if a class implements the __invoke method, it can be used as a callable:

The Positive class implements the __invoke magic method that returns true if the argument is positive, otherwise, it returns false.

You can pass an instance of the Positive class to the array_filter function for including only positive numbers in the result array.

Passing elements to the callback function

By default, array_filter function passes the value of each array element to the callback function for filtering.

Sometimes, you want to pass the key, not value, to the callback function. In these cases, you can pass ARRAY_FILTER_USE_KEY to the third argument of the array_filter function. For example:

In this example, $filtered contains all elements of the $inputs array except for the element whose key is password.

To pass both key and value of the array element to the callback function, you pass theĀ ARRAY_FILTER_USE_BOTH value to the third parameter of the array_filter function.

In this tutorial, you have learned how to to use the PHP array_filter function to filter elements of an array using a callback.

  • Was this tutorial helpful ?
  • YesNo