The for loop is the most used and the most complex loop. However it's usage is not so complicated. The definition of the for statement looks like this:
for (expr1; expr2; expr3) statement
As you can see with 3 expressions it is really more complex than a while loop.
What does these expressions means? Let's discuss it one-by-one.
- expr1: This expression is called only once and this is the first statement which is executed during the loop lifetime. In general loop variable initialization used to be here.
- expr2: This condition is checked in each iteration. If it is true then the statement will be executed.
- expr3: As final step of each iteration this code will be executed.
Let's see a real example how it looks like:
Code:
for ($i=0;$i<10;$i++) echo "$i<br/>";
As you can see here we first initialised the $i variable with 0. Afterwards we defined a condition which is true until the value of $i is less than 10. As last step we increment the value of the variable to avoid endless loop. As result the echo statement will be executed 10 times printing out its actual value.
As usual you can use code blocks instead of only one statement. However in case of only one statement I recommend to use code blocks between {} as it can eliminate some further problem.
Code:
Of course you can change the value of the loop variable inside the loop, but be careful with this solution.
Code:
As in case of while loop you can control the for loop as well from inside the code block. You can break the loop or force to start a new iteration immediately.
So if you want to terminate the loop you can do it by calling the break command like this:
Code:
And if you want to start the next iteration without ending the execution of actual code block you can use continue as follows:
Code:
No comments:
Post a Comment