PHP

PHP Filter Array of Objects by Multiple Criteria

Efficiently filter a PHP array of objects or associative arrays using multiple criteria. Get precise data selection for reports, UI, or complex logic.

function filter_array_by_criteria(array $data, array $criteria): array
{
    return array_filter($data, function($item) use ($criteria) {
        foreach ($criteria as $key => $value) {
            if (!isset($item[$key]) || $item[$key] !== $value) {
                return false; // Item does not match all criteria
            }
        }
        return true; // Item matches all criteria
    });
}

// Example usage:
$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'active' => true],
    ['id' => 2, 'name' => 'Bob', 'role' => 'editor', 'active' => true],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin', 'active' => false],
    ['id' => 4, 'name' => 'David', 'role' => 'viewer', 'active' => true]
];

$filteredUsers = filter_array_by_criteria($users, ['role' => 'admin', 'active' => true]);
print_r($filteredUsers);
/* Expected Output:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [role] => admin
            [active] => 1
        )
)*/
How it works: This function `filter_array_by_criteria` allows you to filter an array of associative arrays (or objects, with slight modification for property access) based on multiple key-value pairs. It iterates through each item, and for every criterion, it checks if the item's corresponding key exists and matches the specified value. Only items that satisfy ALL provided criteria are included in the resulting filtered array. This is invaluable for dynamic data filtering 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