PHP Tutorial - PHP break






When used inside loops, break causes PHP to exit the loop and carry on immediately after it.

Syntax

break;

or

break level;

Example

exit a for loop with break statement

<?php
        for ($i = 1; $i < 10; $i = $i + 1) {
                if ($i == 3) continue;
                if ($i == 7) break;
                print "Number $i\n";
        }
?>

The code above generates the following result.





Example 2

break only exits the containing loop.

<?PHP
     for ($i = 1; $i < 3; $i = $i + 1) {
             for ($j = 1; $j < 3; $j = $j + 1) {
                     for ($k = 1; $k < 3; $k = $k + 1) {
                             print "I: $i, J: $j, K: $k\n";
                             break;
                     }
             }
      }
?>

The code above generates the following result.





Example 3

You can exercise even more control by specifying a number after break, such as break 2, to break out of two loops or switch/case statements. For example:

<?PHP
     for ($i = 1; $i < 3; $i = $i + 1) {
             for ($j = 1; $j < 3; $j = $j + 1) {
                     for ($k = 1; $k < 3; $k = $k + 1) {
                             print "I: $i, J: $j, K: $k\n";
                             break 2;
                     }
             }
      }
?>

The code above generates the following result.

The break command applies to both loops and switch/case statements. For example:

<?PHP
     for ($i = 1; $i < 3; $i = $i + 1) {
             for ($j = 1; $j < 3; $j = $j + 1) {
                     for ($k = 1; $k < 3; $k = $k + 1) {
                             switch($k) {
                                     case 1:
                                             print "I: $i, J: $j, K: $k\n";
                                             break 2;
                                     case 2:
                                             print "I: $i, J: $j, K: $k\n";
                                             break 3;
                             }
                     }
             }
      }
?>

The code above generates the following result.