PHP

Filtering Arrays with a Callback Function

Learn how to use array_filter in PHP to efficiently remove elements from an array that do not meet a specified condition, using a custom callback function.

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter out odd numbers (keep 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 active users
$activeUsers = array_filter($users, function($user) {
    return $user['active'];
});

echo "
Active users:
";
print_r($activeUsers);
?>
How it works: The `array_filter()` function iterates over an array, passing each value to a user-defined callback function. If the callback function returns `true`, the value is included in the resulting filtered array; otherwise, it's excluded. This is highly efficient for conditional data selection, allowing you to easily refine datasets based on specific criteria without manual loops.

Need help integrating this into your project?

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

Hire DigitalCodeLabs