[PHP] Add all previous numbers in a for loop
#1

I have this simple for loop:

Код:
for($i = 1; $i <= 7; $i++) {

    echo $i . "<br>";

}
Which outputs:

Код:
1
2
3
4
5
6
7
Now what I want is to add all the previous numbers on each loop. So the output should be:

Код:
1
2 // current number + all above
3 // current number + all above
6 // current number + all above
12 // current number + all above
24 // current number + all above
48 // current number + all above
I tried this:

Код:
$sum = 0;

for($i = 1; $i <= 7; $i++) {

    $sum = $sum + $i;

    echo $sum . "<br>";

}
But this is the output I get:

Код:
1
3
6
10
15
21
28
How can I get the desired results?
Reply


Messages In This Thread

Forum Jump:


Users browsing this thread: 3 Guest(s)