The array_reduce()
function in PHP is used to iteratively reduce an array to a single value by applying a user-defined callback function to its elements. This function is particularly useful for performing operations like summation, concatenation, or any other kind of aggregation.
array_reduce(array $array, callable $callback, mixed $initial = null): mixed
null
.In this example, we demonstrate how to use array_reduce()
to calculate the sum of an array.
<?php
$array = [1, 2, 3, 4, 5];
$sum = array_reduce($array, function($carry, $item) {
return $carry + $item;
}, 0);
echo "Sum: " . $sum . "\n"; // Output: Sum: 15
?>
Sum: 15
In this case, the callback function adds each element of the array to an accumulated value ($carry
), starting from 0
. The result is the total sum of the array elements.
You can also use array_reduce()
to concatenate strings from an array.
<?php
$array = ["Hello", " ", "World", "!"];
$concatenated = array_reduce($array, function($carry, $item) {
return $carry . $item;
}, "");
echo "Concatenated String: " . $concatenated . "\n"; // Output: Concatenated String: Hello World!
?>
Concatenated String: Hello World!
Here, the callback function concatenates each string element, starting with an empty string.
array_reduce()
can be used to count the occurrences of values in an array.
<?php
$array = ["apple", "banana", "apple", "orange", "banana", "apple"];
$counted = array_reduce($array, function($carry, $item) {
if (!isset($carry[$item])) {
$carry[$item] = 0;
}
$carry[$item]++;
return $carry;
}, []);
print_r($counted);
?>
Array
(
[apple] => 3
[banana] => 2
[orange] => 1
)
In this example, the callback function counts how many times each fruit appears in the array, returning an associative array with the counts.
If you call array_reduce()
on an empty array without an initial value, it will return null
.
<?php
$array = [];
$result = array_reduce($array, function($carry, $item) {
return $carry + $item;
});
echo "Result: " . ($result === null ? 'null' : $result) . "\n"; // Output: Result: null
?>
Result: null
array_reduce()
is useful for:array_reduce($array, $callback, $initial)
reduces an array to a single value by applying a callback function to its elements.@aCodeTutorials All Rights Reserved
privacy policy | about