PHP
Filter an Array Using a Callback Function
Discover how to selectively remove elements from a PHP array based on custom criteria defined by a callback function, ideal for data cleaning and refinement.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter for even numbers
$evenNumbers = array_filter($numbers, function($number) {
return $number % 2 === 0;
});
// $evenNumbers will be [2, 4, 6, 8, 10]
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35],
];
// Filter for users older than 28
$adultUsers = array_filter($users, function($user) {
return $user['age'] > 28;
});
/*
$adultUsers will be:
[
0 => ['name' => 'Alice', 'age' => 30],
2 => ['name' => 'Charlie', 'age' => 35]
]
*/
?>
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 returns `true`, the current value is included in the result array; otherwise, it's skipped. This allows for highly flexible and dynamic filtering logic based on any condition you can express in the callback function.