PHP » Control Structures » break

Syntax:
break [n]
n
Number of levels to stop.

Stops the execution of a block of code.

The execution of all loop control structures and switch can be stopped with the break statement. If there are nested control structures, and more than one level should be stopped, a number of levels can be specified.

Examples

Code:
<?php

for ($i = 0; $i < 10; $i++) {
   print "$i ";
   if ($i == 7)
      break;
}

print "<br><br>";

for ($i = 0; $i < 10; $i++) {
   for ($j = 0; $j < 10; $j++) {
      print "$i: $j ";
       if ($j == 5)
           break;
       if ($i == 6)
          break 2;
   }
   print "<br>";
}

?>
Output:
0 1 2 3 4 5 6 7

0: 0 0: 1 0: 2 0: 3 0: 4 0: 5
1: 0 1: 1 1: 2 1: 3 1: 4 1: 5
2: 0 2: 1 2: 2 2: 3 2: 4 2: 5
3: 0 3: 1 3: 2 3: 3 3: 4 3: 5
4: 0 4: 1 4: 2 4: 3 4: 4 4: 5
5: 0 5: 1 5: 2 5: 3 5: 4 5: 5
6: 0
Explanation:

This code shows how break can be used with one or more levels of nested control statements.

See Also: