php
  1. php-break

Break - Control Statements in PHP

Control statements like break and continue are used to control the flow of execution of a program. In this tutorial, we will focus on the break statement in PHP.

Understanding the Break Statement

Syntax:

The break keyword is used to exit from a loop prematurely. It can be used with while, do...while, for, and switch statements.

while (condition) {
  // Code to be executed
  if (break_condition){
    break;
  }
}

Example:

Let's consider an example of a do...while loop that prints numbers from 1 to 10. We will assume that the loop needs to be exited when the number 5 is encountered.

$num = 1;
do {
  echo $num . "<br>";
  $num++;
  if ($num == 6) {
    break;
  }
} while ($num <= 10);

Output:

The output of the code above will be:

1
2
3
4
5

Explanation:

In the example above, the do...while loop is used to print numbers from 1 to 10. The break statement is used to exit the loop prematurely when the number 5 is encountered. As a result, only the numbers from 1 to 5 are printed.

Use

The break statement is used to exit a loop prematurely in PHP. It can be useful when certain conditions are met, and you need to stop executing the loop.

Important Points

  • The break statement is used to exit a loop prematurely in PHP.
  • It can be used with while, do...while, for, and switch statements.

Summary

In this tutorial, we focused on the break statement in PHP. We covered the syntax, example, output, explanation, use, and important points to provide a better understanding of how the break statement works and when it should be used. The break statement is an essential control statement that helps control the flow of execution of a PHP program.

Published on: