This example has been given as an alternative example (example 4 to be precise) for writing for
loops on PHP.net.
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
I understand for
loops, I just don’t understand why the variable, $j
, is declared in this version of writing a for loop that prints the numbers 1 to 10.
FYI: Removing the variable from the for loop makes absolutely no difference to the result.
We can print numbers from 1 to 10 by using for loop. You can easily extend this program to print any numbers from starting from any value and ending on any value. The echo command will print the value of $i to the screen. In the next line we have used the same echo command to print one html line break.
The PHP for Loop The for loop is used when you know in advance how many times the script should run.
I think that it's just here for illustrate the fact that you can use multiple statement with commas.
It's useless here but show an example of the syntax for :
[...] Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. [...]
While it doesn't seem to be necessary in this example. It appears that $j
is storing the summation of the iterations:
1+2+3+4+5+6+7+8+9+10 = 55
Which can be useful in some situations. So that would mean this style of looping is for the equivalent of doing several operations on each iteration, such as getting the summation, average, largest value, etc. The point of the example is that you can apply several statements separated by commas.
Explanation
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
for loops takes three part separated by semicolon (;).
Increment or Decrements.
Now in your increment or decrements part you have three task.
1. is increment $j with last $i
2. print $i
3. increment $i by 1
So in your program $j is not useful. Because it is not taking part of either print or compare and test.
So the loop is just very simple if you remove $j from every where and write it as
for ($i = 1; $i <= 10; $i++){
print $i;
}
But that $j variable could be used after the loop where from you have taken this code block.
LIKE
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
print $j;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With