PHP : Break

In PHP, the break statement is used to exit from a loop prematurely. It can be used with foreach, for, while, or do-while loops to stop the loop execution based on a certain condition. Here's how you can use break:


foreach ($array as $value) {
    // code to be executed for each iteration

    if ($condition) {
        break; // exit the loop if condition is met
    }
}

 

In this syntax:

  • break is the keyword used to exit the loop.
  • It can be placed inside the loop body.
  • When PHP encounters the break statement, it immediately terminates the loop and continues executing the code after the loop.

Here's an example of using break in a foreach loop:


$numbers = array(1, 2, 3, 4, 5);

foreach ($numbers as $number) {
    echo $number . "<br>";

    if ($number == 3) {
        break; // exit the loop when $number is 3
    }
}

echo "Loop ended.";

This will output:


1
2
3
Loop ended.

 

In this example, the loop stops when the value of  $number becomes 3 because the break statement is encountered. After the loop, Loop ended. is echoed, indicating that the loop has indeed been exited prematurely.