Using PHP's array_filter() Function 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 from a numeric array and removing empty values from an associative array—to demonstrate flexible array filtering techniques.
In PHP programming, arrays are a common data type, and filtering array elements is a frequent operation. PHP offers 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.
Usage syntax:
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )Parameters: $array: the array to be filtered. $callback: a user‑defined function that receives an element and returns true to keep it or false to discard it; if omitted, elements that are falsey are removed by default. $flag (optional): determines how many arguments the callback receives. The default 0 passes only the value; a value greater than 0 also passes the key as the second argument.
Below are two examples demonstrating the use of array_filter():
Example 1: Filtering Even Numbers
<?php
// Original array
$arr = [1, 2, 3, 4, 5, 6];
// Filtering 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 produces:
Array
(
[1] => 2
[3] => 4
[5] => 6
)Example 2: Filtering Empty Values from an Associative Array
<?php
// Original array
$arr = ['name' => 'Tom', 'age' => '', 'gender' => 'male', 'email' => ''];
// Filtering function
function filter_empty($value) {
return ($value !== '');
}
// Apply array_filter()
$new_arr = array_filter($arr, 'filter_empty');
// Output result
print_r($new_arr);
?>The output is:
Array
(
[name] => Tom
[gender] => male
)These examples show two typical scenarios for using array_filter(). In real projects, the function can be applied to many other filtering needs, offering a concise and powerful way to process arrays.
In summary, array_filter() is a widely used PHP function that enables flexible array element filtering through callbacks, helping developers implement various data‑cleaning and selection tasks efficiently.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
