PHP
Filtering an Array by a Custom Condition
Learn how to filter elements from a PHP array using a custom callback function, returning only elements that satisfy a specific condition.
<?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', 'active' => true],
['id' => 2, 'name' => 'Bob', 'active' => false],
['id' => 3, 'name' => 'Charlie', 'active' => true],
];
// Filter active users
$activeUsers = array_filter($users, function($user) {
return $user['active'] === true;
});
echo "Active Users:
";
foreach ($activeUsers as $user) {
echo "- " . $user['name'] . "
";
}
?>
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 function returns `true`, the value is included in the new filtered array; otherwise, it is excluded. This is highly useful for selecting subsets of data based on specific criteria from numerical or associative arrays.