0

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?

3
  • 1
    This sounds a little like homework btw, is it? In any case, you'll have to keep track of the total of the previous values in the array and add that to the current value of the array in each iteration. Commented Mar 19, 2014 at 18:21
  • This isn't homework. years since I was at school. I'm a newbie. Commented Mar 19, 2014 at 18:24
  • @StevenPHP Did you check my answer below? Commented Mar 19, 2014 at 18:27

1 Answer 1

4
$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++;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I tried something very similar. Where you have += it tired .=. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.