php array filter array_filter() function

PHP array_filter() Function With Practical Examples

Used before category names. Blog PHP

The array_filter() is a built-in PHP function used to filter elements from an array using a built-in PHP function or a custom user-defined callback function. This function is used to remove elements from a PHP array that don’t match the given criteria.

array_filter(array, callback, flag);

The array_filter() function takes two arguments, an array, and a callback function. The array argument is the array that needs to be filtered. The callback argument is the function that will be used to determine which elements should be removed from the array.

The array_filter() function passes each value of an input array to the callback function. If the callback function returns true, the current value from array is returned into the result array otherwise not. The callback function has to return a true or false value.

Array keys are preserved, and may result in gaps if the array was indexed.

arrayRequiredSpecifies the array to filter
callbackOptionalThe callback function. It can be PHP built-in function or a user-defined one. If no callback is supplied, all empty entries of the array will be removed.
Since PHP 8.0.0 this function can be nullable.
flagOptionalSpecifies what arguments are sent to the callback:
ARRAY_FILTER_USE_KEY – passes key as the only argument to callback instead of the value
ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value
Default is 0 which will pass the value as the only argument to callback instead.
Returned ValueReturns the filtered array.

This function is available in PHP since version 4.0.6.

An example of a built-in PHP function:

$cars = array(1 => 'Ferrari', 2 => 2, 3 => 'BMW');

var_dump(array_filter($cars, 'is_string'));

Output

array (size=2)
  1 => string 'Ferrari' (length=7)
  3 => string 'BMW' (length=3)

This example checks if the element is a string or not.

An example of a user-made function:

$cars = array(1 => 'Ferrari', 2 => 2, 3 => 'BMW');

function findString($value)
{
    return is_string($value);
}

var_dump(array_filter($cars, 'findString'));

Output

array (size=2)
  1 => string 'Ferrari' (length=7)
  3 => string 'BMW' (length=3)

ARRAY_FILTER_USE_KEY

PHP 5.6 introduced the third parameter to array_filter() called flag, which you could set to ARRAY_FILTER_USE_KEY  to filter by key instead of a value.

ARRAY_FILTER_USE_BOTH

You can set it to ARRAY_FILTER_USE_BOTH  to filter by key or value.

How to filter array by key and value by PHP array_filter()

To filter the array by its keys or values, you can use the “flag” option like the following code.

Filter by key:

$cars = array(1 => 'Ferrari', 2 => 'Benz', 3 => 'BMW', 4 => 'Volvo');

var_dump(array_filter($cars, function ($key) {
    return $key == 2;
}, ARRAY_FILTER_USE_KEY));

Output

array (size=1)
  2 => string 'Benz' (length=4)

Filter by key and value

$cars = array(1 => 'Ferrari', 2 => 'Benz', 3 => 'BMW', 4 => 'Volvo');

var_dump(array_filter($cars, function ($value, $key) {
    return $key == 4 || $value == 'Ferrari';
}, ARRAY_FILTER_USE_BOTH));

Output

array (size=2)
  1 => string 'Ferrari' (length=7)
  4 => string 'Volvo' (length=5)

Filtering a multi-dimensional array in PHP

PHP provides a variety of functions and methods to filter a multi-dimensional array. The most commonly used are array_filter(), array_map(), and array_walk().

An array can be filtered using the array_filter() function based on a callback function. The array element is passed to the callback function as a parameter, and it returns true or false. The element is incorporated into the filtered array if the callback function returns true.

$cars = array(
    array('name' => 'Ferrari', 'rate' => 5),
    array('name' => 'Benz', 'rate' => 5),
    array('name' => 'BMW', 'rate' => 4),
    array('name' => 'Volvo', 'rate' => 4)
);

var_dump(array_filter($cars, function ($car) {
    return $car['rate'] == 5;
}));

Output

array (size=2)
  0 => 
    array (size=2)
      'name' => string 'Ferrari' (length=7)
      'rate' => int 5
  1 => 
    array (size=2)
      'name' => string 'Benz' (length=4)
      'rate' => int 5

Remove empty and null values from the array

The array_filter() function can be used to filter out elements from an array based on various criteria. For example, it can be used to remove all elements from an array that has a value of 0 or less.

$filtered_array = array_filter($myArray, function($element) {
   return $element > 0;
});

This code will create a new array, $filtered_array, which contains only those elements from $myArray that have a value greater than 0.

You can use PHP array_filter() function to remove empty or null values of the array. To do this, ignore the callback function part.

$cars = array(1 => 'Ferrari', 2 => '', 3 => 'BMW', 4 => null);

var_dump(array_filter($cars));

Output:

array (size=2)
  1 => string 'Ferrari' (length=7)
  3 => string 'BMW' (length=3)

You can remove any value from the array that presents empty, null, or zero values.

$entry = array(
    0 => 'foo',
    1 => false,
    2 => -1,
    3 => null,
    4 => '',
    5 => '0',
    6 => 0,
);

var_dump(array_filter($entry));

Output

array (size=2)
  0 => string 'foo' (length=3)
  2 => int -1

Filter array without array_filter() function in PHP

If you don’t want to use the array_filter() function, you have alternatives for that function. You could use for or foreach loop or any other loop instead.

$cars = array(1 => 'Ferrari', 2 => 'Benz', 3 => 'BMW', 4 => 'Volvo');

$filtered_cars = [];

foreach ($cars as $key => $value) {
    if ($key == 2) {
        $filtered_cars[$key] = $value;
    }
}

var_dump($filtered_cars);

Output:

array (size=1)
  2 => string 'Benz' (length=4)

This example accesses each element and checks if its key is 2 or not. If the element’s key is 2, the value will be added to the filtered_cars array. Mostly it is like searching in the array or array iteration.

Read More: Add an element to the PHP array

As you see, you have to do more effort and code to filter the array in this method.

Using PHP array_filter callback as a method of a class

You can pass a method of a class to the array_filter() function. The method should return a true or false value.

array_filter($array, [$instance, 'callback']);
$cars = array(1 => 'Ferrari', 2 => 'Benz', 3 => 'BMW', 4 => 'Volvo');

class Obj
{
    public function isFerrari($value)
    {
        return $value === 'Ferrari';
    }
}

var_dump(array_filter($cars, array(new Obj, 'isFerrari')));

Output:

array (size=1)
  1 => string 'Ferrari' (length=7)

If you have a class that has a static method, you pass the static method as the callback of the array_filter() function, you could use the below syntax.

array_filter($array, ['className', 'callback']);

For example:

$cars = array(1 => 'Ferrari', 2 => 'Benz', 3 => 'BMW', 4 => 'Volvo');

class Obj
{
    public static function isFerrari($value)
    {
        return $value === 'Ferrari';
    }
}

var_dump(array_filter($cars, array('Obj', 'isFerrari')));

Output

array (size=1)
  1 => string 'Ferrari' (length=7)

Conclusion

The array_filter() function is a very useful tool for filtering out elements from an array. It is particularly useful for filtering out elements from an array based on specific criteria.

More