PHP
Filter Array of Associative Arrays by Property
Learn how to efficiently filter an array containing multiple associative arrays (or objects) based on the value of a specific key or property using PHP's array_filter.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'status' => 'active'],
['id' => 2, 'name' => 'Bob', 'status' => 'inactive'],
['id' => 3, 'name' => 'Charlie', 'status' => 'active'],
['id' => 4, 'name' => 'David', 'status' => 'pending'],
];
// Filter to get only active users
$activeUsers = array_filter($users, function($user) {
return $user['status'] === 'active';
});
echo "Active Users:
";
print_r($activeUsers);
// Filter to get users with ID > 2
$usersWithIdGreaterThanTwo = array_filter($users, function($user) {
return $user['id'] > 2;
});
echo "
Users with ID > 2:
";
print_r($usersWithIdGreaterThanTwo);
?>
How it works: This snippet demonstrates using `array_filter` to select elements from an array of associative arrays based on custom criteria. It takes the array and a callback function. The callback function is executed for each element, and if it returns `true`, the element is included in the new filtered array. This is extremely useful for retrieving specific subsets of data from complex arrays, such as filtering a list of users by their status or ID.