PHP
Filtering an Array by Custom Condition
Learn how to selectively filter elements from a PHP array based on a custom callback function, effectively creating a new array with only desired values.
<?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;
});
print_r($oddNumbers);
// Output: Array ( [0] => 1 [2] => 3 [4] => 5 [6] => 7 [8] => 9 )
$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);
/* Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[active] => 1
)
[2] => Array
(
[id] => 3
[name] => Charlie
[active] => 1
)
)
*/
?>
How it works: The `array_filter()` function is used to filter elements of an array using a callback function. It iterates over each value in the input array, passing it to the provided callback function. If the callback function returns `true`, the current value from the input array is included in the result array; otherwise, it is skipped. This is highly useful for creating subsets of arrays based on specific conditions without manual loops.