Using PHP array_filter to Filter Arrays with Practical Examples
This article explains how to use PHP's built-in array_filter function to filter array elements based on custom conditions, demonstrating basic syntax and three practical examples—including filtering odd numbers, strings longer than five characters, and using class methods as callbacks—along with code snippets and output results.
In PHP development, filtering arrays is a common task, and the built-in array_filter function provides a flexible way to keep elements that satisfy a given condition.
The function signature is:
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )where $array is the input array, $callback is an optional function that returns true for elements to keep, and $flag controls callback behavior.
Example 1 shows how to filter odd numbers from an integer array using an anonymous function:
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$filteredNumbers = array_filter($numbers, function($value) {
return $value % 2 == 1;
});
print_r($filteredNumbers);The output is:
Array
(
[0] => 1
[2] => 3
[4] => 5
[6] => 7
[8] => 9
)Example 2 filters strings longer than five characters from an array of names, using strlen inside the callback:
$names = ['John', 'Peter', 'Alice', 'David', 'Sarah'];
$filteredNames = array_filter($names, function($value) {
return strlen($value) > 5;
});
print_r($filteredNames);The resulting array contains:
Array
(
[2] => Alice
[3] => David
)Example 3 demonstrates using a class method as the callback. A Filter class defines an isPositive method, and an instance is passed to array_filter:
class Filter {
public function isPositive($value) {
return $value > 0;
}
}
$numbers = [-1, 2, -3, 4, -5];
$filter = new Filter();
$filteredNumbers = array_filter($numbers, [$filter, 'isPositive']);
print_r($filteredNumbers);The output shows the positive numbers:
Array
(
[1] => 2
[3] => 4
)In summary, array_filter is a powerful PHP function that simplifies array filtering; complex conditions can be handled with anonymous functions or class methods, making it a valuable tool for backend developers.
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.
