In PHP, the array_filter() and array_reduce() functions are very useful tools, which are used to filter and aggregate arrays respectively. They can help developers simplify code, improve code readability and efficiency. This article will use examples to demonstrate how to use these two functions for data filtering and aggregation.
The array_filter() function is used to filter elements in an array. It receives an array and a callback function as parameters. The callback function judges each element in the array. If the callback function returns true , the element is retained in the result array; if false is returned, the element is filtered out.
array_filter(array $array, callable $callback = null, int $mode = 0): array
$array : an array that needs to be filtered.
$callback : The callback function. If the function returns true , the element will be retained; if false is returned, the element will be removed. If the callback function is not passed in, all false values in the array (e.g. null , false , 0 , '' , etc.) are removed.
$mode : optional, specifying the index method to return the array. The default value is 0 , that is, the original index is retained.
Suppose we have an array of numbers that we want to filter out all numbers greater than 10.
<?php
$array = [1, 5, 8, 12, 15, 2];
$result = array_filter($array, function($value) {
return $value > 10;
});
print_r($result);
?>
Output:
Array
(
[3] => 12
[4] => 15
)
In the above code, we use the array_filter() function to filter out numbers greater than 10. As you can see, the returned array contains only elements that meet the criteria.
The array_reduce() function is used to simplify an array into a single value. It operates on each element in the array through a callback function and aggregates the results into a single return value. Common application scenarios include summing, calculating average values, splicing strings, etc.
array_reduce(array $array, callable $callback, $initial = null): mixed
$array : an array that needs to be aggregated.
$callback : The callback function, which receives two parameters: the accumulated value and the value of the current array element. The return value of the callback function will be used as the accumulated value for the next iteration.
$initial : optional, initial value, default is null .
We have an array containing numbers and want to calculate the sum of all elements in the array.
<?php
$array = [1, 5, 8, 12, 15, 2];
$sum = array_reduce($array, function($carry, $value) {
return $carry + $value;
}, 0);
echo $sum;
?>
Output:
43
In the above code, the array_reduce() function adds each element in the array in sequence, and finally returns the sum of the array. Here $carry represents the accumulated value, while $value represents the value of the current array element.
We can use array_filter() and array_reduce() to filter array data and aggregate it. Suppose we have an array of multiple product prices, want to filter out products with prices greater than 10 and calculate their sum.
<?php
$products = [
['name' => 'Product 1', 'price' => 5],
['name' => 'Product 2', 'price' => 15],
['name' => 'Product 3', 'price' => 8],
['name' => 'Product 4', 'price' => 20],
];
// use array_filter Filter out the price is greater than10Products
$filteredProducts = array_filter($products, function($product) {
return $product['price'] > 10;
});
// use array_reduce Calculate the total price of the product after filtering
$totalPrice = array_reduce($filteredProducts, function($carry, $product) {
return $carry + $product['price'];
}, 0);
echo "Total Price: " . $totalPrice;
?>
Output:
Total Price: 35
In this example, we first use array_filter() to filter out products with prices greater than 10, and then use array_reduce() to calculate the sum of these filtered product prices.
Suppose we have an array containing some URLs and need to replace the domain name in it with m66.net , we can do this using array_map() and regular expressions.
<?php
$urls = [
'http://example.com/page1',
'https://www.example.com/page2',
'http://example.com/page3'
];
$updatedUrls = array_map(function($url) {
return preg_replace('/https?:\/\/[^\/]+/', 'https://m66.net', $url);
}, $urls);
print_r($updatedUrls);
?>
Output: