Saturday, August 16, 2008

PHP for loop tutorial - Break and continue the for loop

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:

  1. for ($i=0;$i<10;$i++) echo "$i<br/>";

PHP F1



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:

  1. for ($i=0;$i<10;$i++) {

  2. echo "$i<br/>";

  3. echo "-------<br/>";

  4. }

PHP F1



Of course you can change the value of the loop variable inside the loop, but be careful with this solution.



Code:

  1. for ($i=0;$i<10;$i++) {

  2. echo "$i<br/>";

  3. echo "-------<br/>";

  4. $i++;

  5. }

PHP F1



 



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:

  1. for ($i=0;$i<10;$i++) {

  2. echo "$i<br/>";

  3. echo "-------<br/>";

  4. if ($i==5) break;

  5. }

PHP F1



And if you want to start the next iteration without ending the execution of actual code block you can use continue as follows:



Code:

  1. for ($i=0;$i<10;$i++) {

  2. if ($i==2) continue;

  3. echo "$i<br/>";

  4. echo "-------<br/>";

  5. }

PHP F1

No comments: