Using PHP array_filter() to Filter Arrays
This article explains the PHP array_filter() function, its signature and parameters, and demonstrates how to filter numeric arrays and associative arrays with custom callbacks through clear code examples and output results.
In PHP programming, arrays are a fundamental data type, and filtering array elements is a common operation. PHP provides the useful array_filter() function to accomplish this.
The array_filter() function applies a callback to each element of an array, keeping elements that satisfy the condition and returning a new array.
Its usage is as follows:
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )Parameter details:
$array : the array to be filtered.
$callback : a user‑defined function that receives an element (and optionally its key) and returns true to keep the element or false to discard it. If omitted, elements evaluating to false are removed by default.
$flag : optional flag indicating how many arguments the callback receives. The default 0 passes only the element; a value greater than 0 also passes the element’s key.
Below are two examples illustrating the use of array_filter() :
Example 1: Filtering Even Numbers from an Indexed Array
<?php
// Original array
$arr = [1, 2, 3, 4, 5, 6];
// Callback function
function filter_even($value) {
return ($value % 2 == 0);
}
// Apply array_filter()
$new_arr = array_filter($arr, 'filter_even');
print_r($new_arr);
?>Running the code outputs:
Array
(
[1] => 2
[3] => 4
[5] => 6
)Example 2: Removing Empty Values from an Associative Array
<?php
// Original array
$arr = [
'name' => 'Tom',
'age' => '',
'gender' => 'male',
'email' => ''
];
// Callback function
function filter_empty($value) {
return ($value !== '');
}
// Apply array_filter()
$new_arr = array_filter($arr, 'filter_empty');
print_r($new_arr);
?>The result is:
Array
(
[name] => Tom
[gender] => male
)In summary, array_filter() is a versatile PHP function that enables flexible array filtering by leveraging custom callbacks, making it easy to implement a wide range of filtering scenarios in backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.