break

break 结束当前 forforeachwhiledo-while 或者 switch 结构的执行。

break 可以接受一个可选的数字参数来决定跳出几重循环。

<?php
$arr
= array('one', 'two', 'three', 'four', 'stop', 'five');
while (list (,
$val) = each($arr)) {
    if (
$val == 'stop') {
        break;    
/* You could also write 'break 1;' here. */
    
}
    echo
"$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++
$i) {
    switch (
$i) {
    case
5:
        echo
"At 5<br />\n";
        break
1;  /* Exit only the switch. */
    
case 10:
        echo
"At 10; quitting<br />\n";
        break
2;  /* Exit the switch and the while. */
    
default:
        break;
    }
}
?>


add a note add a note User Contributed Notes
traxer at gmx dot net
30-Dec-2005 10:53
vlad at vlad dot neosurge dot net wrote on 04-Jan-2003 04:21

> Just an insignificant side not: Like in C/C++, it's not
> necessary to break out of the default part of a switch
> statement in PHP.

It's not necessary to break out of any case of a switch  statement in PHP, but if you want only one case to be executed, you have do break out of it (even out of the default case).

Consider this:

<?php
$a
= 'Apple';
switch (
$a) {
   default:
       echo
'$a is not an orange<br>';
   case
'Orange':
       echo
'$a is an orange';
}
?>

This prints (in PHP 5.0.4 on MS-Windows):
$a is not an orange
$a is an orange

Note that the PHP documentation does not state the default part must be the last case statement.
develop at jjkiers dot nl
13-Jul-2005 05:06
To php_manual at pfiff-media dot de:

This is only possible with PHP5, because <PHP5 doesn't have a proper exception infrastructure.
php_manual at pfiff-media dot de
14-Mar-2005 10:21
instead of using the while (1) loop with break like suggested in an earlier note, I would rather recommend throwing an exception, e.g.:

<?php
try
{
 
$query = "SELECT myAttr FROM myTable";
 
$db = DB::connect($dbUrl);
if (
DB::isError($db)) {
  
throw new Exception("Connection failed");
  }
 
/* ... */
} catch (Exception $e) {
  echo
"Error: ".$e->getMessage()."</br>";
}
?>
Ilene Jones
22-Feb-2005 05:08
For Perl or C programmers...

break is equivelant to last

while(false ! == ($site = $d->read()) ) {
  if ($site === 'this') {
     break;  // in perl this could be last;
  }
}
abodeman at yahoo
18-May-2004 02:28
The use of "break n" to break out of n enclosing blocks is generally a pretty dangerous idea. Consider the following.

Let's say you have a text file that contains some lines of text, as most text files do. Let's also say that you are writing a little piece of PHP to parse each line and interpret it as a string of commands. You might first write some test code just to interpret the first character of each line, like this:

<?php
$num
= 0;
$file = fopen("input.txt", "r");
while (!
feof($file)) {
  
$line = fgets($file, 80);
   switch (
$line{0}) {
      
// Arbitrary code here--the details aren't important
      
case 'i': // increment
          
echo ++$num." ";
           break;
       case
'f': // find factors
          
for ($factor = 1; $factor <= $num; ++$factor) {
               if (
$num % $factor == 0) {
                   echo
"[".$factor."] ";
                  
// stop processing file if 7 is a factor
                  
if ($factor == 7)
                       break
3; // break out of while loop
              
}
           }
   }
}
fclose($file);
?>

So, now that you have this magnificent piece of test code written and working, you would want to make it parse all the characters in each line. All you have to do is put a loop around the switch statement, like so:

<?php
$num
= 0;
$file = fopen("input.txt", "r");
while (!
feof($file)) {
  
$line = fgets($file, 80);
   for (
$i = 0; $i < strlen($line); ++$i) {
       switch (
$line{$i}) {
          
// Arbitrary code here--the details aren't important
          
case 'i': // increment
              
echo ++$num." ";
               break;
           case
'f': // find factors
              
for ($factor = 1; $factor <= $num; ++$factor) {
                   if (
$num % $factor == 0) {
                       echo
"[".$factor."] ";
                      
// stop processing file if 7 is a factor
                      
if ($factor == 7)
                           break
3; // break out of while loop
                  
}
               }
       }
   }
}
fclose($file);
?>

(Of course, you changed "$line{0}" to "$line{$i}", since you need to loop over all the characters in the line.)

So now you go and try it out, and it doesn't work. After a bunch of testing, you discover that when 7 is a factor, the code stops processing the current line, but continues to process the remaining lines in the file. What happened?

The problem is the "break 3;". Since we added another loop, this doesn't break out of the same loop it did before. In a small program like this, it's not too difficult to find this problem and fix it, but imagine what it would be like if you have thousands of lines of PHP with a numbered break statement hidden in the mess somewhere. Not only do you have to find it, you also have to figure out how many layers you want to break out of.

Unfortunately, PHP doesn't really offer any alternative to numbered break statements. Without line labels, there's no way to refer to a specific loop. There is also no "goto" statement in PHP. You could kludge your way around things with something like
<?php
do {
  
// some code
  
if ($condition)
       break;
  
// some more code
} while (FALSE);
?>
or
<?php
switch ($dummy) {
   default:
      
// some code
      
if ($condition)
           break;
      
// some more code
}
?>
but these sorts of tricks quickly add an enormous amount of clutter to your code.

Thus, the moral of the story is simply to be very careful when using numbered break statements. The numbered break statement is one of the few language features that can break silently when other code is changed.
2et at free dot fr
17-Mar-2004 09:48
If you need to execute a sequence of operations, where each step can generate an error, which you want to interrupt the sequence and you don't want to have an incrementing if...then...else/elseif indenting like this:

<?php
// Level 0 indenting.
$query = "SELECT myAttr FROM myTable";
$db = DB::connect($dbUrl);
if (
DB::isError($db)) {
  
// Level 1 indenting.
  
echo "Error: Connection failed.<br/>";
} else {
  
$dbResult = $db->query($query);
   if (
DB::isError($dbResult)) {
      
// Level 2 indenting.
      
echo "Error: Query failed.<br/>";
   } else {
      
// ...
  
}
}
?>

First, elseif can be used to prevent indent level increase by replacing:

<?php
--
} else {
  
$dbResult = $db->query($query);
   if (
DB::isError($dbResult)) {
      
// Level 2 indenting.
--
by
--
} elseif (
DB::isError($dbResult = $db->query($query))) {
  
// Level 1 indenting SUCCESS!
--
?>

However, it's not possible every time, because you can't reasonably put everything between the else and the if keywords in the if condition like above. Therefore, I suggest the following little trick using while and break:

<?php
while(1) {
// Level 1 indenting.
  
$query = "SELECT myAttr FROM myTable";
  
$db = DB::connect($dbUrl);
   if (
DB::isError($db)) {
      
// Level 2 indenting.
      
echo "Error: Connection failed.<br/>";
      
// Exit sequence.
      
break;
   }
  
// Back to level 1.
  
$dbResult = $db->query($query);
   if (
DB::isError($dbResult)) {
      
// Level 2 indenting.
      
echo "Error: Query failed.<br/>";
      
// Exit sequence.
      
break;
   }
  
// Back to level 1.
   // ...
   // Quit while.
  
break;
}
?>

Using do { ... } while(0) is even better, because the last break keyword can be removed.

Note: If you intend to use other statements using break (while, switch, for, foreach...) in the while(1) { ... } statement (or do while...), you can still exit using break's argument:

<?php
while (1) {
   while(
cond) {
       if (
error) {
           break
2;
       }
   }
}
?>
jody at redstarmedia dot org
05-Mar-2004 12:06
If you are careful about repeating code when using multiple cases that pretty much do the same thing, you can use multiple cases for one block of code / one break. Below is an example.
<?php
switch($var)
  {
     case
'foo':
     case
'bar':
          
//Processing code
    
break;
  }
?>
vlad at vlad dot neosurge dot net
04-Jan-2003 05:21
Just an insignificant side not: Like in C/C++, it's not necessary to break out of the default part of a switch statement in PHP.