PHP
Efficiently Filter PHP Arrays by Custom Condition
Learn how to use `array_filter` in PHP to easily remove elements from an array based on a user-defined callback function, keeping only desired values.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out even numbers, keeping only odd numbers
$oddNumbers = array_filter($numbers, function($number) {
return $number % 2 !== 0;
});
print_r($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;
});
print_r($activeUsers);
?>
How it works: This snippet demonstrates `array_filter`, a powerful PHP function for filtering array elements. It iterates through an array, passing each value to a user-defined callback function. If the callback returns `true`, the element is kept in the new filtered array; otherwise, it's discarded. This allows for highly flexible and custom filtering logic, useful for cleaning or subsetting data.