PHP
Filter PHP Array by Multiple Key-Value Conditions
Discover how to filter a PHP array of associative arrays by matching multiple specific key-value pairs using a custom function for precise data selection.
<?php
$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'],
];
/**
* Filters an array of associative arrays based on multiple key-value conditions.
*
* @param array $array The input array.
* @param array $conditions An associative array of key-value pairs to match.
* @return array The filtered array.
*/
function filterByMultipleConditions(array $array, array $conditions): array
{
return array_filter($array, function ($item) use ($conditions) {
foreach ($conditions as $key => $value) {
if (!isset($item[$key]) || $item[$key] !== $value) {
return false; // Mismatch found for one condition
}
}
return true; // All conditions matched
});
}
// Filter users who are 'active' AND 'admin'
$activeAdmins = filterByMultipleConditions($users, ['status' => 'active', 'role' => 'admin']);
/*
$activeAdmins will be:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[status] => active
[role] => admin
)
[3] => Array
(
[id] => 4
[name] => David
[status] => active
[role] => admin
)
)
*/
print_r($activeAdmins);
?>
How it works: This snippet provides a reusable function `filterByMultipleConditions` to filter an array of associative arrays based on multiple key-value pairs. It leverages `array_filter` with a callback that iterates through the specified conditions. An item is included in the result only if it matches all provided key-value conditions, offering a flexible way to perform complex filtering operations.