Using PHP's array_filter() to Filter Arrays
This article explains how PHP's array_filter() function works, details its parameters, and provides two practical code examples—filtering even numbers and removing empty values from an associative array—to demonstrate flexible array filtering techniques.
In PHP programming, arrays are a fundamental data type, and filtering array elements is a common operation. PHP offers the useful array_filter() function to accomplish this task.
The array_filter() function applies a callback to each element of an array, keeping only those elements that satisfy the callback's condition and returning a new array.
Usage syntax:
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )Parameter description:
$array : the array to be filtered.
$callback : a user‑defined function that receives an array element and returns true to keep the element or false to discard it. If omitted, the function removes elements that are falsy.
$flag (optional): determines how many arguments are passed to the callback. The default 0 passes only the value; a value greater than 0 also passes the key as a second argument.
Example 1 – Filtering even numbers:
<?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');
// Output result
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');
// Output result
print_r($new_arr);
?>Running the code outputs:
Array
(
[name] => Tom
[gender] => male
)These examples show two typical scenarios for using array_filter() . In real‑world development, the function has many other applications, and developers can adapt it to various filtering needs.
In summary, array_filter() is a widely used and practical PHP function that provides a convenient way to filter array elements using custom logic, enabling flexible data processing in backend applications.
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.