PHP provides a multitude of powerful functions for manipulating arrays, and one such function is array_filter()
. In this article, you will learn that array_filter() is a PHP function used to filter elements from an array by key or value using a built-in PHP function or a custom user-defined callback function based on a specified condition by example. This function is used to remove elements from a PHP array that don’t match the given criteria.
Whether you need to remove certain values, extract specific elements, or create a new array based on a custom filtering logic, array_filter() is an indispensable tool in your PHP development arsenal.
$cars = array(1 => 'Ferrari', 2 => 2, 3 => 'BMW');
function findString($value)
{
return is_string($value);
}
var_dump(array_filter($cars, 'findString'));
We will discuss more about the array_filter to filter an array with multiple PHP methods in the following. Let’s dive in.
PHP array_filter() to filter an array with an example
This PHP built-in function is a powerful and versatile function used to filter the elements of an array. The array_filter() function in PHP is designed to iterate over an array and apply a user-defined callback function to each element.
It takes a callback function as its first argument, which we use to determine which features will be included in the resulting array. The PHP array_filter() can be used to filter out an array of elements based on a variety of criteria. Such as value, key, or even user-defined function.
array_filter(array, callback, flag);
The PHP array_filter() function takes two arguments, an array, and a filter callback function. The PHP array argument is the array that we want to filter. 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 in PHP. 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.
array | Required | Specifies the array to filter |
callback | Optional | The 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. |
flag | Optional | Specifies what arguments are sent to the callback:ARRAY_FILTER_USE_KEY – passes key as the only argument to callback instead of the valueARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the valueDefault is 0 which will pass the value as the only argument to callback instead. |
Returned Value | Returns the filtered array. |
This function is available in PHP since version 4.0.6.
An example of a built-in PHP array_filter() function to filter an array:
$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 uses the array_filter function to filter the array and check if the element is a string or not in PHP.
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 the array by key instead of a value.
This is an optional flag we use for the array_filter() function in PHP. It is used to filter an array based on the keys of the array instead of the values.
If the callback function returns TRUE, the current element will be in the result array, if FALSE the function excludes it.
$numbers = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$filteredNumbers = array_filter($numbers, function ($key) {
return $key === 'b';
}, ARRAY_FILTER_USE_KEY);
print_r($filteredNumbers);
Output
Array ( [b] => 2 )
In this example, the given value to the function is the key of the array, not the value.
ARRAY_FILTER_USE_BOTH
You can set it to ARRAY_FILTER_USE_BOTH to filter the PHP array by key or value.
$numbers = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$filteredNumbers = array_filter($numbers, function ($value,$key) {
return $key == 'b' || $value == 4;
}, ARRAY_FILTER_USE_BOTH);
print_r($filteredNumbers);
Output
Array ( [b] => 2 [d] => 4 )
The ARRAY_FILTER_USE_BOTH accepts both the key and value of the array and filters the array based on the given parameters in the PHP array filter function. The only note here is, that the first parameter is the value and the second parameter is the key.
Filter Elements of a PHP array based on a condition
In this example, we use PHP array_filter() to extract only the even numbers from the $numbers array.
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter even numbers
$filteredNumbers = array_filter($numbers, function ($value) {
return $value % 2 === 0;
});
print_r($filteredNumbers);
Output
[2, 4, 6, 8, 10]
The second way to filter an array is to filter it by using the user-defined function. For example
function even($var)
{
return $var % 2 === 0;
}
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$filteredNumbers = array_filter($numbers, 'even');
print_r($filteredNumbers);
Output
Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
In this example, we defined the even()
function to check if the given value is even or not. To filter even numbers of the array, we pass the even() function to PHP built-in array_filter() function.
How to filter array by key and value by PHP array_filter()
To filter the array by its key or value, you can use the PHP “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().
We can filter an array using the PHP 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
We use the array_filter() function to filter out elements from an array based on various criteria in PHP. For example, in the below example, we use PHP array_filter 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 the 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
Remove empty strings, false and null values but not 0 value from an array
If you want to remove empty string, false, and null values from an array and leave the 0 numbers in it, you should use strlen
built-in function as the callback function in the parameters.
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => '',
5 => '0',
6 => 0,
);
$result = array_filter( $entry, 'strlen' );
var_dump($result);
Output
array (size=4)
0 => string 'foo' (length=3)
2 => int -1
5 => string '0' (length=1)
6 => int 0
Filter array without array_filter() function in PHP with example
If you don’t want to use the PHP 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 PHP 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)
PHP array_filter function and JSON
In unfiltered arrays, if you want to encode the array to JSON, the keys will be the keys in JSON. But in filtered arrays, the key no longer exists.
$cars = array(1 => 'Ferrari', 2 => 'Benz', 3 => '', 4 => 'Volvo');
$result = array_filter( $cars, 'strlen' );;
var_dump(json_encode($result));
Output
{"1":"Ferrari","2":"Benz","4":"Volvo"}
In this example, we filtered the cars array and removed the empty string in the 4th element and after that encoded the array to create JSON, but there are no keys in the JSON. array_filter function removes the keys of the array.
Conclusion
The array_filter() function is a handy PHP tool to filter out elements from an array. It is particularly useful for filtering out elements from an array based on specific criteria.