控制结构
在线手册:中文 英文
PHP手册

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";
}

/* 使用可选参数 */

$i 0;
while (++
$i) {
    switch (
$i) {
    case 
5:
        echo 
"At 5<br />\n";
        break 
1;  /* 只退出 switch. */
    
case 10:
        echo 
"At 10; quitting<br />\n";
        break 
2;  /* 退出 switch 和 while 循环 */
    
default:
        break;
    }
}
?>


控制结构
在线手册:中文 英文
PHP手册
PHP手册 - N: break

用户评论:

Anonymous (15-Feb-2012 02:51)

Correction to [Miguel Cruz 15-Apr-2009 12:37], at least in php 5.3: "'break 0', while allowed, does nothing" is not true.  break 0 (and break -1) act just like break without an argument or break 1.

Here's the code (which also confirms the findings of [RK 17-Dec-2010 04:09]) --

<?php
function break_level($i) {
    while (
true) :
      break
$i;
      echo
"printed WITHIN function control structure when \$i = " . $i . "<br />";
    endwhile;
   
    echo
"printed AFTER function control structure when \$i = " . $i . "<br />";
}

break_level(-1); // => outputs "printed AFTER function control structure when $i = -1"
break_level(0);  // => outputs "printed AFTER function control structure when $i = 0"
break_level(1);  // => outputs "printed AFTER function control structure when $i = 1"
break_level(2);  // => Fatal error: "Cannot break/continue 2 levels in [program_name] on line 4"

echo "printed after LAST CALL to function when \$i = " . $i . "<br />";
?>

RK (17-Dec-2010 12:09)

If the numerical argument is higher than the number of things which can be broken out of, it seems to me like the execution of the entire program is stopped.
My program had 8 nested loops. Didn't bother counting them, but wrote: break 10. - Result: Code following the loops was not processed.

Miguel Cruz (15-Apr-2009 08:37)

To make it very clear, if you use "break" with no numerical argument, that's the same as doing "break 1".

"break 0", while allowed, does nothing.

webmaster at kayfer dot com (07-Feb-2009 06:03)

Ok guys here something that I use and it works

<?php

                                               
switch($_GET['id'])

{

default:
      echo
"yourvalue\n";
      echo
"yourvalue2\n";
break;

case
banner:
      echo
"content in banner\n";
      echo
"another content in banner\n";
break;

case
header:
      echo
"content in header\n";
      echo
"another content in header\n";
break;

case
other:
      echo
"content in other\n";
      echo
"another content in other\n";
break;

}

?>

Now I will explain what each script does.

first part the

<?php

                                               
switch($_GET['id'])

{

should be included or it won't work

default is default link, lets say if this is in index.php then when index.php is loaded default will be shown.

case banner: or case header: or case other: is what will be hidden until visitors click on link that will take them there, the value after case is going to be added after the name of the file, lets say case banner: is in index.php then case banner: and its contents will be in index.php?id=banner same for header and other cases. note that you always should put break; tag should be included.

Hope this helped you guys, I am sorry if i didn'
t explain it well but I tried my best.

Coryf88 at hotmail dot com (30-Aug-2008 09:51)

Breaks are not required within a switch, they simply break the switch from being further processed.
<?php
$total
= 0;
switch(
$i) {
    case
6:
       
$total = 99;
    break;
    case
1:
       
$total += 1;
    case
2:
       
$total += 2;
    case
3:
       
$total += 3;
    case
4:
       
$total += 4;
    case
5:
       
$total += 5;
}
?>
Using the above snippet, all of the following would be true:
If $i = 6, $total would = 99.
If $i = 5, $total would = 5.
If $i = 4, $total would = 9.
If $i = 3, $total would = 12.
If $i = 2, $total would = 14.
If $i = 1, $total would = 15.

Anonymous (14-Aug-2008 05:54)

The previous note has a somewhat stupid author: why didn't you put an example?

If I got it right, "case"s in "switch"es always need a "break".
So this switch ...

<?php
switch ( $i ) {
  case
'1': // Works
   
echo "$i=1";
    break;
  case
'2': // Works
   
require( 'include1.inc' );
    break;
  case
'3': // Doesn't work
   
require( 'include2.inc' );
    break;
  case
'4': // Doesn't work, same reason
   
require( 'include2.inc' );
  default:
// Works
   
echo "$i";
}
?>

... has a problem in case "4" in that it doesn't have a "break" and this file...

include2.inc:
<?php
 
echo "$i";
  break;
?>

... has a problem in that it has a "break" that is not in a "control structure" (like while, for...).

In the same way, although "include2.inc" is "include"d (obvioulsy) in the <?php ?> script (of main.php), it still need another <?php ?> to wrap its content.

Likewise,

main.php
<?php
echo "<div>This div is generated by php</div>\n";
include
'file.php'; ?>
echo "<div>This div is also generated by php</div>\n";

file.php:
<div>This is an old static HTML div.</div>

... doesn't require "file.php" content to start with "?>" (exit php) and end with "<?php" (go back to line 3 of main.php). This would FAIL.

(See strange structure ALWAYS fail"?>!)

Does this really need documentation?

Anonymous (11-Aug-2008 07:43)

Your break doesn't work because it isn't within a control structure.  I use includes that have breaks and they work fine because they are in a control structure (foreach, while, etc.)

cb (08-Jul-2008 11:01)

Just to note: break doesn't work within included file, results in fatal error.

main.php:
<?php
switch ( $i )
{
  case
'1': // Works
   
echo "$i";
    break;
  case
'2': // Works
   
require( 'include1.inc' );
    break;
  case
'3': // Doesn't work
   
require( 'include2.inc' );
    break;
  case
'4': // Doesn't work, same reason
   
require( 'include2.inc' );
  default:
// Works
   
echo "$i";
}
?>

include1.inc:
<?php
 
echo "$i";
?>

include2.inc:
<?php
 
echo "$i";
  break;
?>

I didn't find this documented anywhere.

alan at synergymx dot com (15-Apr-2008 08:06)

Here is a function that returns specific files in an array, with all of the details. Includes some basic garbage checking.

Variables

$source_folder // the location of your files
$ext // file extension you want to limit to (i.e.: *.txt)
$sec // if you only want files that are at least so old.
$limit // number of files you want to return

The function

function glob_files($source_folder, $ext, $sec, $limit){
    if( !is_dir( $source_folder ) ) {
        die ( "Invalid directory.\n\n" );
    }
   
    $FILES = glob($source_folder."\*.".$ext);
    $set_limit    = 0;
   
    foreach($FILES as $key => $file) {
   
        if( $set_limit == $limit )    break;
       
        if( filemtime( $file ) > $sec ){
       
            $FILE_LIST[$key]['path']    = substr( $file, 0, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['name']    = substr( $file, ( strrpos( $file, "\\" ) +1 ) );   
            $FILE_LIST[$key]['size']    = filesize( $file );
            $FILE_LIST[$key]['date']    = date('Y-m-d G:i:s', filemtime( $file ) );
            $set_limit++;
       
        }
       
    }
    if(!empty($FILE_LIST)){
        return $FILE_LIST;
    } else {
        die( "No files found!\n\n" );
    }
}

So....

$source_folder = "c:\temp\my_videos";
$ext = "flv"; // flash video files
$sec = "7200"; // files older than 2 hours
$limit = 2; // Only get 2 files

print_r(glob_files($source_folder, $ext, $sec, $limit));

Would return:

Array
(
    [0] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => fluffy_bunnies.flv
            [size] => 21160480
            [date] => 2007-10-30 16:48:05
        )

    [1] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => synergymx.com.flv
            [size] => 14522744
            [date] => 2007-10-25 15:34:45
        )

Gautam (22-Aug-2007 10:53)

<?php
/*
break :break command exits the innermost loop construct which contains it.
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

You can view various output by changing comparision operator(<,==,>) or value of $limit
*/
$to_square_root=65536;
$i=1;
$limit=4;
while (
true) {
$square_root=sqrt($to_square_root);
echo
"Square Root of $to_square_root is $square_root.<BR>";
$to_square_root=$square_root;
$i=$i+1;
if (
$i>$limit) // if ($i<$limit) is used, loop breaks on very first execution
break;
}
$loop=$i-1;
echo
"This loop is executes for $loop times.";
/* Above codes produces following output in browser
Square Root of 65536 is 256
Square Root of 256 is 16
Square Root of 16 is 4
Square Root of 4 is 2
This loop is executes for 4 times
*/
?>

pinkgothic at gmail dot com (22-Jun-2007 12:10)

To add to the responses given to "vlad at vlad dot neosurge dot net" - I'd like to note the lack of automatic breaking in 'default' can be a very good thing. Consider this useful snippet:

<?php

switch((string) $_REQUEST['mode']) {
  default:
    
$_REQUEST['mode'] = "search";
    
// fall through...
 
case 'search' :
  case
'list' :
  case
'add' :
  case
'edit' :
     require(
dirname(__FILE__)."/incs/".$_REQUEST['mode'].".php");
     break;
}

?>

I personally find that far easier to look at than, for example:

<?php

$valid_modes
= array('search','list','add','edit');
if (
in_array($_REQUEST['mode'],$valid_modes)) {
     require(
dirname(__FILE__)."/incs/".$_REQUEST['mode'].".php");
} else {
     require(
dirname(__FILE__)."/incs/search.php");
}

?>

...and it even has the added benefit that the switch() variant only has one require() statement, which makes for easier maintenance, e.g. if the directory changes, or what-have-you.

(Consider the above pseudocode, please, it's not tested - it's code illustrating a point only.)

vinyanov at poczta dot onet dot pl (05-May-2007 01:36)

Note that the break argument accepts any expression, including a function result. So you may want to dynamically choose the loop level to break from:

<?php

// the print() function returns 1

function icarus()
{
    while(print(
'sea level, '))
        while(print(
'through the clouds, '))
            while(print(
'close the Sun - '))
                break
rand(print('FEATHERS LOSS! - '), 3);
   
    print(
'no feathers remaining.');
}

icarus();

?>

(18-Jan-2007 02:12)

If you wonder how to end execution of a function (as I did), it's that simple: return

function foo($a) {
 if(!$a) return;
 echo 'true';
 // some other code
}

foo(true) will echo 'true', foo(false) won't echo anything (as return ends execution of the function. Of course, therefore there is no need for 'else' before 'echo').

clean_code at is_good_code dot com (08-Nov-2006 08:07)

"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."

--Yes it is, it's just that traditionally default: is the last entry of a switch and so nothing happens after.

-If it was, for whatever reason, not the last entry the script would bawk, there is no implicit break; associated with switch.

traxer at gmx dot net (30-Dec-2005 02: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.

Ilene Jones (21-Feb-2005 09: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;
  }
}