PHP
Filtering PHP Arrays with array_filter
Learn how to selectively remove elements from a PHP array based on custom criteria using the array_filter() function and a user-defined callback for powerful data manipulation.
<?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);
// Expected 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'];
});
print_r($activeUsers);
/*
Expected 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 iterates over each value in an array, passing it to a user-defined callback function. If the callback function returns `true`, the value is kept in the resulting array; otherwise, it's removed. This allows for highly flexible filtering based on any custom logic you define, making it incredibly useful for data sanitization or selection.