PHP
Filter an Array Based on a Dynamic Condition
Efficiently filter elements from a PHP array by applying a custom callback function, allowing you to select only items 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;
});
print_r($oddNumbers);
// Output:
// Array
// (
// [0] => 1
// [2] => 3
// [4] => 5
// [6] => 7
// [8] => 9
// )
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35]
];
// Filter users older than 28
$olderUsers = array_filter($users, function($user) {
return $user['age'] > 28;
});
print_r($olderUsers);
// Output:
// Array
// (
// [0] => Array
// (
// [name] => Alice
// [age] => 30
// )
//
// [2] => Array
// (
// [name] => Charlie
// [age] => 35
// )
// )
?>
How it works: `array_filter()` iterates over each value in an array, passing it to a user-defined callback function. If the callback function returns `true`, the value is included in the filtered array; otherwise, it's excluded. This function is highly effective for selectively extracting elements from an array based on any complex condition you define, without needing explicit loops.