PHP
Filter an Array Based on a Custom Condition
Learn how to efficiently filter elements from a PHP array using a callback function with array_filter, keeping only items that meet specific criteria.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out even numbers
$oddNumbers = array_filter($numbers, function($number) {
return $number % 2 !== 0;
});
echo "Original Numbers: " . implode(", ", $numbers) . "
";
echo "Odd Numbers: " . implode(", ", $oddNumbers) . "
";
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25],
['id' => 3, 'name' => 'Charlie', 'age' => 30],
];
// Filter users older than 28
$olderUsers = array_filter($users, function($user) {
return $user['age'] > 28;
});
echo "Original Users:
";
print_r($users);
echo "Users Older Than 28:
";
print_r($olderUsers);
?>
How it works: This snippet demonstrates `array_filter()`, a powerful PHP function used to filter elements of an array using a callback function. For each element, the callback function is executed, and if it returns `true`, the element is included in the new filtered array. This is highly useful for selecting data based on arbitrary conditions without manual looping.