PHP

Filtering an Array with a Custom Callback Function

Discover how to use `array_filter()` in PHP to selectively keep elements from an array that meet a specific, user-defined condition, such as filtering odd numbers or active users.

<?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;
});
echo "Even Numbers:
";
print_r($evenNumbers);

$users = [
    ['id' => 1, 'name' => 'Alice', 'active' => true],
    ['id' => 2, 'name' => 'Bob', 'active' => false],
    ['id' => 3, 'name' => 'Charlie', 'active' => true]
];

// Filter for active users
$activeUsers = array_filter($users, function($user) {
    return $user['active'];
});
echo "
Active Users:
";
print_r($activeUsers);
?>
How it works: `array_filter()` is a powerful PHP function for filtering elements of an array using a callback function. It iterates over each value in the array, passing it to the provided callback. If the callback function returns `true`, the element is kept in the resulting array; otherwise, it is discarded. This snippet demonstrates filtering a simple numeric array for even numbers and an array of associative arrays for active users, showcasing its versatility for various filtering criteria.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs