• PHP also has two keywords break and continue to control the loop, just like another programming language.
  • Those statements are known as the flow of transfer or jumping statements in the program.

Break

  • The break statement is used inside the for loop, foreach loop, while loop and do-while loop and then switch case statement.
  • Inside a loop the break statement encountered then it immediately terminated the loop statement and transferred the control to the next statement, followed by a loop to resume the execution.
  • In nested loop statement it is also used, where it breaks the inner loop first and then proceed to break the outer loop.
  • In program it is also used in the switch case statement to terminate a particular case’s execution.
  • A break statement is placed inside the loop with a condition and then if the condition is true, a break statement is immediately executed to break the execution of the loop and to move the control to the next statement followed by the loop.

Sample Code

<?php    

// defines the for loop   

for ($a = 0; $a < 10; $a++) {  

  if ($a == 7) {  

    break; /* Break the loop when condition is true. */  

  }  

  echo "Number: $a <br>";  

}  

echo " Terminate the loop at $a number";  

?>  

Output

Continue

  • It is used in the middle of for loop, while loop, do-while loop and for-each loop.
  • In a loop the continue statement is encountered then it skips the current iteration of the loop.
  • A continue statement is usually used with a condition inside a loop and then if the condition is true, the continue statement is executed to skip the iteration.
  • It transfers the control to the beginning of the loop for further execution inside the loop, after that.

Sample Code

<?php    

// defines the for loop   

for ($a = 0; $a < 7; $a++) {  

  if ($a == 5) {  

  echo " Skipped number is $a <br>"; // prints the skipped number.  

    continue; /* It skips the defined statement if the condition is true. */  

  

  }  

  echo "Number is: $a <br>";  

}  

?>

 Output

Categorized in: