Definition and Usage
- PHP Version
- 4.0.6+
The array_filter()
function filters elements of an array using a callback function.
Using this function, you can easily filter an array to keep only the values you want.
By writing the condition as a callback function, it returns a new array containing only the elements that satisfy the condition.
Features
- The filtering condition is applied in a callback function:
The callback should returntrue
for elements that meet the condition, andfalse
for those that do not. - The original array is not modified. Instead, the function returns a new array containing only the elements that pass the filter.
- The filtered elements retain their original keys (indices) from the array.
Basic Example
This example demonstrates how to use the array_filter()
function to filter only the even numbers from an array and return a new array containing those filtered values.
// Array to filter
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Developer-defined callback function
function isEven($value) {
return $value % 2 == 0; // Return true for even numbers
}
// Return a filtered array
$evenNumbers = array_filter($numbers, 'isEven');
print_r($evenNumbers);
/*
Output: The original array keys (indices) are preserved
Array
(
[1] => 2
[3] => 4
[5] => 6
[7] => 8
[9] => 10
)
*/
Syntax
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Parameters
$array |
Required. The array to be filtered. |
---|---|
$callback |
Optional. A callback function to process each element of the array. The callback receives each element as an argument and should return true or false . Returning true keeps the element in the filtered array; returning false excludes it. If no callback is provided, all empty entries are removed from the array. Since PHP 8.0.0, omitting the callback triggers an E_WARNING . |
$mode |
Optional. A flag determining what is passed to the callback. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH . With ARRAY_FILTER_USE_KEY , the callback receives only the key, which is useful for filtering based on keys in an associative array. With ARRAY_FILTER_USE_BOTH , the callback receives both the value and the key, allowing filtering using both. The default value is 0, which passes only the value to the callback. |
Return Values
The function returns a filtered array. The filtered elements retain their original keys (indices) from the array.
How the Callback Function Works
The array_filter()
function filters the elements of a given array using a developer-defined callback function according to the specified condition, and returns a new array containing only the elements that satisfy that condition.
The callback function in array_filter()
is used to determine whether each element should be included in the filtered array. It is called for each element of the array, and based on the result (true
or false
), the element is either included or excluded. Below is a step-by-step explanation of how the callback function is executed within array_filter()
:
array_filter()
/**
* Callback function
*
* @param mixed $element Each element of the array
* @return bool Return true if the element meets the filtering condition, false otherwise
*
* Can be a named function (user-defined) or an anonymous function.
*/
// Using a named function as a callback
function callback($element) { // Define a named function
// Filtering logic: return true for elements that should be included
}
array_filter($array, 'callback'); // Pass the name of the defined function as a string parameter
// Using an anonymous function as a callback
array_filter($array, function($element) {
// Filtering logic: return true for elements that should be included
});
Execution sequence of array_filter()
:
- Call
array_filter()
and pass the array to be filtered as the first parameter. - Pass a callback function as the second parameter. This callback is called for each element of the array.
array_filter()
selects the first element of the array and passes it as the argument ($element
) to the callback function.- The callback function is executed. Inside the callback, you can apply the required condition and use the
return
statement to determine whether the element satisfies the filtering criteria. - If the callback returns
true
, the element is included in the filtered array. If it returnsfalse
, the element is excluded. array_filter()
repeats this process for each element in the array.- After all elements have been processed,
array_filter()
returns a new array containing only the elements that passed the filter. - The returned array contains only the elements for which the callback returned
true
.
In this way, the callback function in array_filter()
allows you to filter an array based on developer-defined conditions, enabling a wide range of filtering operations.
Important Notes
Preserving Original Array Indices
The array_filter()
function returns a new array containing only the filtered elements while keeping the original keys (indices) intact. Therefore, the keys (indices) in the filtered array remain the same as in the original array.
The example below filters only the even numbers from an array containing numbers 1 through 10:
array_filter()
function returns a new array containing the filtered elements, while preserving the original array's keys (indices).
// Array to filter
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Developer-defined callback function
function isEven($value) {
return $value % 2 == 0; // Return true for even numbers
}
// Return a filtered array
$evenNumbers = array_filter($numbers, 'isEven');
print_r($evenNumbers);
/*
Output: Original array keys (indices) are preserved
Array
(
[1] => 2
[3] => 4
[5] => 6
[7] => 8
[9] => 10
)
*/
// Important note: Accessing indices in the filtered array
var_dump($evenNumbers[0]); // null
One important point to note in this code is that the filtered array, $evenNumbers
, is created by selecting only the even numbers from the original array $numbers
. However, there is no element with a key (index) starting at 0 in the filtered array because the filtered array preserves the original array’s keys (indices). Therefore, accessing the first element using $evenNumbers[0]
will not return the expected value and will instead return null
.
If No Callback Function Is Provided
Starting from PHP 8.0.0, omitting the second parameter (the callback function) in array_filter()
triggers an E_WARNING
.
$data = ['apple', '', 'banana', null, 'cherry'];
// Remove empty values
$filteredData = array_filter($data); // No callback provided
// Output result
print_r($filteredData);
Practical Examples
The array_filter()
function can be used for a variety of array filtering tasks. Here are some examples:
Filtering Elements That Start with a Specific Value
You can use array_filter()
to filter elements that start with a specific character. The following example creates a new array containing only strings that start with "a":
$array = ["apple", "banana", "cat", "dog", "elephant"];
$stringsStartingWithA = array_filter($array, function ($string) {
return $string[0] == "a";
});
print_r($stringsStartingWithA);
/*
Output:
Array
(
[0] => apple
)
*/
Removing Empty Values
Using array_filter()
together with empty()
is very effective for removing empty values from an array. This allows you to clean up the array easily. Here's an example:
$data = ['apple', '', 'banana', null, 'cherry'];
// Provide a callback function to remove empty values
$filteredData = array_filter($data, function ($value) {
return !empty($value);
});
// Output result
print_r($filteredData);
/*
Output:
Array
(
[0] => apple
[2] => banana
[4] => cherry
)
*/
Filtering Associative Arrays Based on a Condition
This example shows how to filter an associative array based on its values. array_filter()
is typically used to filter by value. If you need to consider both keys and values, other approaches may be more suitable.
$scores = [
'Alice' => 85,
'Bob' => 92,
'Carol' => 78,
'David' => 95
];
// Filter students with scores 90 or above
$topScorers = array_filter($scores, function ($value) {
return $value >= 90;
});
// Output result
print_r($topScorers);
/*
Output:
Array
(
[Bob] => 92
[David] => 95
)
*/
References
See also
- PHP isset() and empty() Functions – Concepts, Usage, and Key Differences
- PHP foreach Loop – Usage and Examples
- PHP array_map() Function – Concepts and Practical Examples
- PHP array_reduce() Function – Reducing an Array to a Single Value
- PHP array_key_exists() Function – Check if a Key Exists in an Array
- PHP array_keys() Function – Get a List of Array Keys
- PHP array_search() Function – Searching for a Value in an Array
- JavaScript Array filter() Function