Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need a quick help

I need to sum up the 3 previous values of an array

eg

PHP
array(2, 2, 3, 4, 5, 4, 1, 3, 2);


i would like to get the result like the table below. i want to sum up the last 3 values



ValuesSum
22
24
37
49
512
413
110
38
26

Posted
Updated 17-Sep-13 23:52pm
v2
Comments
Killzone DeathMan 18-Sep-13 7:32am    
Easy like this ;)

$arr = array(2, 2, 3, 4, 5, 4, 1, 3, 2);
$sum = array();

echo 'Original:<br/>';

foreach($arr as $key => $a){
echo $a . '<br/>';

$s = ($arr[$key - 2] + $arr[$key - 1] +$arr[$key]);
$sum[] = $s;
}



echo '<br/>ValuesSum:<br/>';

foreach($sum as $key => $s){
echo $s . '<br/>';


The output of the code is:

Original:
2
2
3
4
5
4
1
3
2

ValuesSum:
2
4
7
9
12
13
10
8
6
Baba_Dee 20-Sep-13 3:44am    
Thanks, I really appreciate your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900