Search code examples
phparraysloopsadditioncumulative-sum

Loop through array adding all previous values to current value


I wish to loop through an array adding the previous value to the current one. This is my latest attempt, but does not output the desired result

$array = array(
    "myKeyName"   => 3,
    "anotherName" => 8,
    "aKeyName"    => 12,
    "keyName"     => 6,
    "anotherKey"  => 34
    );

$setItems = array();

$i = 1;

foreach($array as $key => $val){
    $setItems['item'.$i] = $val+$val;
    $i++;
};

print_r($setItems);

OUTPUT

Array ( [item1] => 6 [item2] => 16 [item3] => 24 [item4] => 12 [item5] => 68 )

DESIRED OUTPUT

Array ( [item1] => 3 [item2] => 11 [item3] => 23 [item4] => 29 [item5] => 63 )

I understand why I am getting the current output, I just don;t know how to change it get get the desired output efficiently. Any ideas?


Solution

  • $array = array(
        "myKeyName"   => 3,
        "anotherName" => 8,
        "aKeyName"    => 12,
        "keyName"     => 6,
        "anotherKey"  => 34
        );
    
    $setItems = array();
    
    $i = 1;
    $previous = 0;
    foreach($array as $key => $val){
        $setItems['item'.$i] = $val+$previous;
        $previous += $val;
        $i++;
    };