Web Info and IT Lessons Blog...

Tuesday, 9 December 2014

Continue and Break in PHP

The previous lesson of PHP Lessons Series was about Array Sorting Functions and in this lesson we will learn about Continue and Break Statements in PHP.

Continue and Break Statements in PHP

PHP Break Statement

A break statement is usually used to break out of the normal flow of a loop or a switch. If a break statement is used in a case of a switch, no more cases after the execution of break will be checked. Similarly if a break statement is used in a loop, there will be no more iterations of the loop after the execution of break statement. An example of PHP break statement is given below:


for ($i=0;$i<10;$i++){
 if($i == 5)
  break;
 echo 'This is iteration number '.$i.'<br />';
} 

The above code shows the use of a break statement in a for loop. The above for loop would normally have had 10 iterations but due to the execution of break statement inside the (if) condition at the 6th iteration of the loop, there will only be 6 iterations of the above loop and the echo statement will be executed 5 times. The output of the above code is given below:

Output:
This is iteration number 0
This is iteration number 1
This is iteration number 2
This is iteration number 3
This is iteration number 4

PHP Continue Statement

A continue statement is usually used in a loop to pass the control back to the top of the loop. When a continue statement is executed inside a loop, no more code after the continue statement will be executed for that specific iteration and the control of the loop will shift back to the top to start a new iteration of the loop. An example of PHP continue statement is given below:


for ($i=0;$i<10;$i++){
 if($i == 5)
  continue;
 echo 'This is iteration number '.$i.'<br />';
} 

The above code shows the use of a continue statement in a for loop. Normally the echo statement in the above for loop would have run 10 times, but due to the use of continue statement in the (if) condition at the 6th iteration of the for loop the control will pass to the top of the loop without running the echo statement. Thus the echo statement will run 9 times in the above for loop skipping just once for the 6th iteration. The output of the above code is given below:

Output:
This is iteration number 0
This is iteration number 1
This is iteration number 2
This is iteration number 3
This is iteration number 4
This is iteration number 6
This is iteration number 7
This is iteration number 8
This is iteration number 9

No comments:

Post a Comment