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
<?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.

Similar Reads

What is a Cumulative Sum Array?

A cumulative sum array is an array where each element at index i is the sum of the elements from the original array up to index i. For example, given the array [1, 2, 3, 4], the cumulative sum array would be [1, 3, 6, 10]....

Using a for Loop

A basic method to create a cumulative sum array is to use a for loop to iterate through the original array and calculate the sum step by step....

Using array_reduce() Function

The array_reduce() function can be used to accumulate values, and we can use it to create a cumulative sum array by keeping track of the sums in an external variable....

Using array_map() Function with Closure

Another approach is to use array_map() with a closure to create the cumulative sum array. This method is more functional and concise....