PHP
Filter Array Elements Based on a Condition
Discover how to selectively remove elements from a PHP array using `array_filter` and a custom callback function, retaining only those 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;
});
// Result: [1, 3, 5, 7, 9] (keys are preserved)
// Re-index the array if desired
$oddNumbersReindexed = array_values($oddNumbers);
// Result: [1, 3, 5, 7, 9] (keys are 0, 1, 2, 3, 4)
$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;
});
// Result: [['id' => 1, 'name' => 'Alice', 'active' => true], ['id' => 3, 'name' => 'Charlie', 'active' => true]]
echo "Odd Numbers: " . json_encode($oddNumbers) . "
";
echo "Odd Numbers (Re-indexed): " . json_encode($oddNumbersReindexed) . "
";
echo "Active Users: " . json_encode(array_values($activeUsers)) . "
";
?>
How it works: The `array_filter()` function is used to iterate over an array, passing each value to a user-defined callback function. If the callback function returns `true`, the element is kept in the new array; otherwise, it is discarded. This allows for highly flexible filtering based on any condition. The original keys are preserved by default, so `array_values()` is often used to re-index the resulting array.