How can the array_reduce function be used to calculate sums in multidimensional arrays with varying numbers of elements?
When dealing with multidimensional arrays with varying numbers of elements, the array_reduce function can be used to calculate sums by recursively iterating through the array and summing up the values. By defining a custom function to handle the addition operation, we can ensure that the array_reduce function works correctly on all levels of the multidimensional array.
function sumArray($arr) {
return array_reduce($arr, function($carry, $item) {
if (is_array($item)) {
return $carry + sumArray($item);
}
return $carry + $item;
}, 0);
}
$multiArray = [
[1, 2, 3],
[4, 5],
[6, [7, 8]],
[9]
];
$totalSum = sumArray($multiArray);
echo $totalSum; // Output: 45