PHP
Filter Associative Arrays with Dynamic Multiple Criteria
Master filtering an array of associative arrays in PHP using a custom function that accepts multiple dynamic criteria, allowing complex conditional data selection.
<?php
function filterAssociativeArray(array $array, array $criteria): array
{
return array_filter($array, function ($item) use ($criteria) {
foreach ($criteria as $key => $value) {
// If the key doesn't exist or its value doesn't match, this item is filtered out
if (!isset($item[$key]) || $item[$key] !== $value) {
return false;
}
}
return true; // All criteria met
});
}
$users = [
['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'status' => 'active'],
['id' => 2, 'name' => 'Bob', 'role' => 'editor', 'status' => 'inactive'],
['id' => 3, 'name' => 'Charlie', 'role' => 'admin', 'status' => 'active'],
['id' => 4, 'name' => 'David', 'role' => 'viewer', 'status' => 'active'],
];
$activeAdmins = filterAssociativeArray($users, ['role' => 'admin', 'status' => 'active']);
/*
Example Output:
[
0 => ["id" => 1, "name" => "Alice", "role" => "admin", "status" => "active"],
2 => ["id" => 3, "name" => "Charlie", "role" => "admin", "status" => "active"]
]
*/
$inactiveEditors = filterAssociativeArray($users, ['role' => 'editor', 'status' => 'inactive']);
/*
Example Output:
[
1 => ["id" => 2, "name" => "Bob", "role" => "editor", "status" => "inactive"]
]
*/
How it works: This snippet provides a `filterAssociativeArray` function that allows filtering an array of associative arrays based on one or more dynamic criteria. It iterates through the criteria, ensuring that each item in the array matches all specified key-value pairs. This offers a flexible way to select specific records from a dataset without hardcoding filtering logic.