[PHP] Add all previous numbers in a for loop - Printable Version
+- SA-MP Forums Archive (
https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (
https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (
https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: [PHP] Add all previous numbers in a for loop (
/showthread.php?tid=664438)
[PHP] Add all previous numbers in a for loop -
Mr.Anonymous - 28.02.2019
I have this simple for loop:
Код:
for($i = 1; $i <= 7; $i++) {
echo $i . "<br>";
}
Which outputs:
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:
How can I get the desired results?
Re: [PHP] Add all previous numbers in a for loop -
Banditul18 - 28.02.2019
Dont get me wrong but this forum is all about pawn and sa-mp.
Re: [PHP] Add all previous numbers in a for loop -
Mr.Anonymous - 28.02.2019
Quote:
Originally Posted by Banditul18
Dont get me wrong but this forum is all about pawn and sa-mp.
|
I mean you can take this as a pawn question since both pawn and php are quite similar.
Re: [PHP] Add all previous numbers in a for loop -
kristo - 28.02.2019
The output you get is correct, it does the thing you described... Your "desired" output is the value of
$i until 3 and from then on it's
3 ^ ($i - 2).
Re: [PHP] Add all previous numbers in a for loop -
benjaminjones - 28.02.2019
Until three, you can make them static, after that simple current number * 2;
Код:
Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
var res = 3;
for (int i = 0; i < 7; i++)
{
res *= 2;
Console.WriteLine(res);
}
Re: [PHP] Add all previous numbers in a for loop -
Mr.Anonymous - 28.02.2019
Quote:
Originally Posted by benjaminjones
Until three, you can make them static, after that simple current number * 2;
Код:
Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
var res = 3;
for (int i = 0; i < 7; i++)
{
res *= 2;
Console.WriteLine(res);
}
|
It's actually not multiplied by 2, it's add all previous numbers on each loop.
Re: [PHP] Add all previous numbers in a for loop -
benjaminjones - 28.02.2019
Quote:
Originally Posted by Mr.Anonymous
It's actually not multiplied by 2, it's add all previous numbers on each loop.
|
If you add all the previous numbers on each loop, the result you get is the same as the result you get, if you start from 3 and multiply from there. The code I provided produces the same result, as the one you've described.