PHP

Filter Multidimensional Array by Multiple Criteria

Discover how to apply complex filtering logic to a multidimensional array, selecting elements that match specific conditions across various keys simultaneously.

<?php
function filter_multidimensional_array(array $array, array $criteria): array {
    return array_filter($array, function ($item) use ($criteria) {
        foreach ($criteria as $key => $value) {
            if (!isset($item[$key]) || $item[$key] !== $value) {
                return false; // Mismatch found for one criterion
            }
        }
        return true; // All criteria matched
    });
}

$users = [
    ['id' => 1, 'name' => 'Alice', 'status' => 'active', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob', 'status' => 'inactive', 'role' => 'user'],
    ['id' => 3, 'name' => 'Charlie', 'status' => 'active', 'role' => 'user'],
    ['id' => 4, 'name' => 'David', 'status' => 'active', 'role' => 'admin']
];

$activeAdmins = filter_multidimensional_array($users, [
    'status' => 'active',
    'role' => 'admin'
]);
// var_dump($activeAdmins);
/* Expected Output (simplified):
[
    ["id" => 1, "name" => "Alice", "status" => "active", "role" => "admin"],
    ["id" => 4, "name" => "David", "status" => "active", "role" => "admin"]
]
*/
?>
How it works: This `filter_multidimensional_array` function helps you narrow down a list of associative arrays based on multiple conditions. It takes the main array and an associative array of criteria (key-value pairs). It iterates through each item, checking if all specified criteria match. Only items that satisfy all conditions are included in the resulting filtered array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs