How to use array_map() Function with Closure In PHP
Another approach is to use array_map() with a closure to create the cumulative sum array. This method is more functional and concise.
- We initialize a variable $sum to store the running total.
- We use array_map() function to apply a closure to each element in the original array. The closure updates $sum and returns it for each element, building the cumulative sum array.
Example: This example shows the creation of an array of cumulative sum using array_map() Function with Closure.
<?php
function cumulativeSum($arr) {
$sum = 0;
return array_map(function($item) use (&$sum) {
$sum += $item;
return $sum;
}, $arr);
}
// Driver code
$arr = [1, 2, 3, 4];
$res = cumulativeSum($arr);
print_r($res);
?>
Output
Array ( [0] => 1 [1] => 3 [2] => 6 [3] => 10 )
Create an Array of Cumulative Sum in PHP
The cumulative sum array is an array where each element is the sum of all previous elements in the original array up to the current index. This article explores different methods to create an array of cumulative sums in PHP.