PHP
Filter an Array Based on a Custom Callback Condition
Learn how to efficiently filter elements from a PHP array using a custom callback function with `array_filter`, retaining only items that meet specific criteria.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out numbers greater than 5
$filteredNumbers = array_filter($numbers, function($number) {
return $number > 5;
});
print_r($filteredNumbers);
echo "
";
$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);
?>
How it works: This snippet demonstrates using `array_filter()` to create a new array containing only elements that satisfy a specific condition. It takes an array and a callback function. The callback function is executed for each element, and if it returns `true`, the element is included in the result; otherwise, it's excluded. This is highly efficient for data subsetting and is flexible for various filtering needs.