In PHP, array_filter and array_map are two very commonly used and powerful array processing functions. They have their own uses when used alone, but when we combine them, we can greatly improve the simplicity and efficiency of the code. This article will introduce the usage of these two functions in detail and share practical tips and best practices for their combination.
array_filter
This function is used to filter array elements. A callback function determines whether each element meets the condition and returns a new array composed of all elements that meet the condition.
$filtered = array_filter($array, function($item) {
return $item > 10; // Filter is greater than10Elements
});
array_map
This function is used to perform the same callback operation on each element of the array, returning the processed new array.
$mapped = array_map(function($item) {
return $item * 2; // Multiply each element by2
}, $array);
After filtering, map : first use array_filter to filter out elements that meet the conditions, and then use array_map to process these elements uniformly.
After mapping, filter : first use array_map to convert the array element format, and then use array_filter to filter the results that meet the requirements.
One-time chain operation : Use in combination to write concise and intuitive chain code, avoiding writing lengthy loops.
<?php
$numbers = [1, 5, 12, 18, 7, 25];
// Filter out the greater than10Numbers
$filtered = array_filter($numbers, function($num) {
return $num > 10;
});
// 再对过滤后Numbers做平方操作
$squared = array_map(function($num) {
return $num * $num;
}, $filtered);
print_r($squared);
?>
Output:
Array
(
[2] => 144
[3] => 324
[5] => 625
)
In this example, first use array_filter to remove elements that do not meet the conditions to avoid array_map from doing useless work.
PHP 7.4+ supports arrow functions, and is more concise in combination with chain calls:
<?php
$numbers = [1, 5, 12, 18, 7, 25];
$result = array_map(
fn($num) => $num * $num,
array_filter($numbers, fn($num) => $num > 10)
);
print_r($result);
?>
<?php
$urls = [
'http://example.com',
'ftp://fileserver.com',
'https://secure.com',
];
// Convert to lowercase protocol first
$lowercased = array_map(fn($url) => strtolower($url), $urls);
// Filter out againhttpThe beginning of the agreementURL
$httpUrls = array_filter($lowercased, fn($url) => str_starts_with($url, 'http'));
print_r($httpUrls);
?>
The second parameter of array_filter ARRAY_FILTER_USE_KEY can be used to filter according to the key name, and then process the value in combination with array_map :
<?php
$data = [
'name' => 'Alice',
'age' => 25,
'email' => '[email protected]',
'score' => 92,
];
// Filter only keeps the key name as string and the length is greater than3Elements
$filtered = array_filter($data, fn($key) => strlen($key) > 3, ARRAY_FILTER_USE_KEY);
// Convert values to string format
$mapped = array_map(fn($value) => (string)$value, $filtered);
print_r($mapped);
?>
Filter first and then map to reduce unnecessary processing.
Map first and then filter, and the data format or structure can be unified first for easy filtering.
Use arrow functions and chain calls to write cleaner code.
Combined with ARRAY_FILTER_USE_KEY to filter key names.
Combination uses make the code logic clearer, avoid complex loops, and improve code reusability and readability.
Mastering the combination and use skills of these two functions can make you more handy in handling arrays in daily PHP development and write efficient and elegant code.
<?php
// Comprehensive examples:Filter out empty values,Convert string to uppercase,Return result
$data = ['apple', '', 'Banana', null, 'Cherry'];
$result = array_map(
fn($item) => strtoupper($item),
array_filter($data, fn($item) => !empty($item))
);
print_r($result);
?>