PHP
Filter Associative Arrays by Key Value
Learn how to efficiently filter an array containing multiple associative arrays, keeping only those elements that match a specific condition on one of their keys in PHP.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
['id' => 2, 'name' => 'Bob', 'role' => 'user'],
['id' => 3, 'name' => 'Charlie', 'role' => 'admin'],
['id' => 4, 'name' => 'David', 'role' => 'guest']
];
// Filter users with the role 'admin'
$admins = array_filter($users, function($user) {
return $user['role'] === 'admin';
});
print_r($admins);
/* Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[role] => admin
)
[2] => Array
(
[id] => 3
[name] => Charlie
[role] => admin
)
)*/
How it works: This snippet demonstrates how to filter an array of associative arrays based on a condition applied to one of their keys. The `array_filter()` function iterates through each element of the `$users` array. For each element (which is an associative array representing a user), the provided anonymous function checks if the 'role' key's value is strictly equal to 'admin'. Only the elements for which the callback returns `true` are included in the resulting `$admins` array.