PHP 7 Fundamental Tutorial for Beginners – PHP Break and Continue Statement

Break statement

The break statement is used with the conditional switch statement and with the do, for, and while loop statements. When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

  • A break statement can be used to terminate or to come out from the loop or conditional statement unconditionally.
  • It can be used in switch statement to break and come out from the switch statement after each case expression.
  • Whenever, break statement is encounter within the program then it will break the current loop or block.
  • A break statement is normally used with if statement.
  • When certain condition becomes true to terminate the loop then break statement can be used

This example jumps out of the loop when x is equal to 4:

Example:

Output:

The number is: 0
The number is: 1
The number is: 2
The number is: 3

Continue statement

Continue statement works like break but instead of forcing termination, it forces the next iteration of the loop to take place and skipping the rest of the code. Continue statement is mostly used inside loops, whenever it is encountered inside a loop, either conditionally or unconditionally, transfers control to the next iteration of either the current loop or an enclosing labelled loop.

  • continue statement can be used into the loop when we want to skip some statement to be executed and continue the execution of above statement based on some specific condition.
  • Similar to break statement, continue is also used with if statement.
  • When compiler encounters continue, statements after continue are skipped and control transfers to the statement above continue.

This example skips the value of 4:

Example:

Output:

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9

Break and Continue in While Loop

You can also use break and continue in while loops:

Break Example

Continue Example

Rajesh Kumar
Follow me