PHP

Filter Array by Multiple Dynamic Criteria

Discover how to filter a PHP array or an array of objects/associative arrays based on multiple, dynamic conditions using `array_filter` with a custom callback.

$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'status' => 'active', 'age' => 30],
    ['id' => 2, 'name' => 'Bob', 'role' => 'editor', 'status' => 'inactive', 'age' => 25],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin', 'status' => 'active', 'age' => 40],
    ['id' => 4, 'name' => 'David', 'role' => 'viewer', 'status' => 'active', 'age' => 35],
];

// Example 1: Filter users who are 'admin' AND 'active'
$activeAdmins = array_filter($users, function($user) {
    return $user['role'] === 'admin' && $user['status'] === 'active';
});
print_r($activeAdmins);

echo "
";

// Example 2: Filter users who are 'editor' OR 'viewer' AND 'age' < 30
$filteredUsers = array_filter($users, function($user) {
    return ($user['role'] === 'editor' || $user['role'] === 'viewer') && $user['age'] < 30;
});
print_r($filteredUsers);

echo "
";

// Example 3: Dynamic filtering function with parameters
function filterUsers(array $users, array $criteria): array
{
    return array_filter($users, function($user) use ($criteria) {
        foreach ($criteria as $key => $value) {
            if (!isset($user[$key]) || $user[$key] !== $value) {
                return false;
            }
        }
        return true;
    });
}

$dynamicFilterResult = filterUsers($users, ['role' => 'admin', 'status' => 'active']);
print_r($dynamicFilterResult);
How it works: This snippet illustrates how to effectively filter a PHP array, specifically an array of associative arrays, based on multiple criteria. It uses the `array_filter` function with anonymous callback functions (closures) to define the filtering logic. The examples demonstrate filtering with simple AND/OR conditions and also introduce a reusable `filterUsers` function that accepts an array of dynamic criteria, making it highly flexible for various data filtering scenarios in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs