PHP
Filter and Map Associative Arrays
Learn to efficiently filter and transform arrays of associative arrays or objects in PHP using `array_filter` and `array_map` for sophisticated data processing.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30, 'active' => true],
['id' => 2, 'name' => 'Bob', 'age' => 24, 'active' => false],
['id' => 3, 'name' => 'Charlie', 'age' => 35, 'active' => true],
['id' => 4, 'name' => 'David', 'age' => 24, 'active' => true]
];
// 1. Filter: Get only active users
$activeUsers = array_filter($users, function($user) {
return $user['active'] === true;
});
// 2. Map: Extract names of active users
$activeUserNames = array_map(function($user) {
return $user['name'];
}, $activeUsers);
print_r($activeUserNames);
// Combined operation: Get names of users older than 25
$olderUserNames = array_map(function($user) {
return $user['name'];
}, array_filter($users, function($user) {
return $user['age'] > 25;
}));
print_r($olderUserNames);
?>
How it works: This snippet demonstrates how to use `array_filter` to select elements from an array based on a condition, and `array_map` to transform each selected element. First, we filter an array of user data to find only 'active' users. Then, we map the results to extract just their names. The second example shows how to chain these operations to filter users older than 25 and then extract their names in a single step, which is a common pattern for data manipulation.