PHP break

Description

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//from   w ww.java  2 s .  c  o  m
        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/*ww  w.  ja v  a  2 s  .com*/
     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//from  w w w .  ja va2  s  . c om
     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/*ww  w . j av  a  2  s  .  c o  m*/
     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.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition