In PHP, array_filter() and array_map() are two very powerful and commonly used array processing functions. The former is used to filter elements in an array, while the latter is used to transform each element in the array. Using them alone can solve many problems, but using the two together can more efficiently process data in complex structures, such as nested arrays, object arrays, or business logic that requires multiple processing steps.
This article will use a practical example to demonstrate how to cleverly combine array_filter() and array_map() to implement filtering and conversion of complex arrays.
Suppose we have an array of users, each user contains information such as name, age, email address, status, etc. Our goals are:
Only users with status "active" are retained;
Convert each user's name to capital;
Only output two fields: name and mailbox;
The example original array is as follows:
$users = [
['name' => 'Alice', 'age' => 25, 'email' => 'alice@m66.net', 'status' => 'active'],
['name' => 'Bob', 'age' => 30, 'email' => 'bob@m66.net', 'status' => 'inactive'],
['name' => 'Charlie', 'age' => 22, 'email' => 'charlie@m66.net', 'status' => 'active'],
];
Let's first use array_filter() to filter out users with active status:
$activeUsers = array_filter($users, function($user) {
return $user['status'] === 'active';
});
After this step is executed, $activeUsers only contains Alice and Charlie.
Next, we capitalize the name with array_map() and keep only the fields we care about (name and email):
$transformedUsers = array_map(function($user) {
return [
'name' => strtoupper($user['name']),
'email' => $user['email']
];
}, $activeUsers);
Output result:
[
['name' => 'ALICE', 'email' => 'alice@m66.net'],
['name' => 'CHARLIE', 'email' => 'charlie@m66.net']
]
If you want the code to be more concise, you can chain the two functions. Although array_filter() itself does not return the array of key resets, it is better to use it with array_values() :
$processedUsers = array_map(function($user) {
return [
'name' => strtoupper($user['name']),
'email' => $user['email']
];
}, array_values(array_filter($users, function($user) {
return $user['status'] === 'active';
})));
Combining array_filter() and array_map() can make it very flexible to process complex arrays, achieving logical separation of "filter first, then convert". This method is very suitable for use in scenarios such as processing API data return, form data preprocessing, and business data flow.
Also, don't forget that if you are dealing with associative arrays or need to preserve key names, you can consider using array_keys() , array_values() or using more advanced functional libraries such as Laravel's Collection class to enhance readability and functionality.
Related Tags:
array_filter array_map