PHP
Filter PHP Arrays Using a Callback
Discover how to efficiently filter elements from a PHP array based on custom conditions using the array_filter function with a user-defined callback.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter for even numbers
$evenNumbers = array_filter($numbers, function($number) {
return $number % 2 === 0;
});
echo "Even Numbers:
";
print_r($evenNumbers);
$users = [
['name' => 'Alice', 'age' => 30, 'active' => true],
['name' => 'Bob', 'age' => 24, 'active' => false],
['name' => 'Charlie', 'age' => 35, 'active' => true]
];
// Filter for active users older than 25
$activeSeniorUsers = array_filter($users, function($user) {
return $user['active'] && $user['age'] > 25;
});
echo "
Active Senior Users:
";
print_r($activeSeniorUsers);
?>
How it works: The array_filter() function iterates over each value in an array, passing it to a user-defined callback function. If the callback returns true, the value is included in the new filtered array; otherwise, it's excluded. This provides a flexible way to select elements based on complex criteria without manual loops.