PHP break

In this chapter you will learn:

  1. What is a break statement
  2. Syntax for break statement
  3. Example - exit a for loop with break statement
  4. Example - Exit only one level of loop
  5. Example - exit more than one level with break statement

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//j  a  v a 2s  .  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//  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   j a v a 2  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/*j  av  a  2 s  . co  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.

Next chapter...

What you will learn in the next chapter:

  1. What is a continue statement
  2. Example - using continue to start the next iteration
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require