I have an array of some values that I need to convert to a new array and sum each value with all previous values. For example (array length, keys and values are always different), this is what I have:
Array ( [0] => 1 [1] => 1 [2] => 5 [3] => 1 [4] => 1 [7] => 1 [8] => 3 [9] => 1 )
and this is what i need:
Array ( [0] => 1 [1] => 2 [2] => 7 [3] => 8 [4] => 9 [7] => 10 [8] => 13 [9] => 14 )
I tried many different ways, but I was always stuck in something or realized that I was wrong somewhere. I feel like I'm trying to invent a wheel here because I think it needs some kind of simple function, but he couldn’t find a solution. This is the last way I tried:
$array = array( "0"=> 1, "1"=> 1, "2"=> 5, "3"=> 1, "4"=> 1, "7"=> 1, "8"=> 3, "9"=> 1 ); $this = current($array); $next = next($array); $end = next(end($array)); $sum = 0; $newArray = array(); foreach ($array as $val){ if($val != $end){ $sum = ($this += $next); array_push($newArray, $sum); } } print_r($newArray);
.. Sorry, wrong again. I spend a lot of time looking for ways to avoid getting to where I should be, can someone hit me in the right direction, please?
source share