• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • break

    (PHP 4, PHP 5, PHP 7)

    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;
        }
    }
    ?>
    
    break的更新记录
    版本说明
    5.4.0break 0;不再合法。这在之前的版本被解析为break 1;
    5.4.0取消变量作为参数传递(例如$num = 2; break $num;)。
    A break statement that is in the outer part of a program (e.g. not in a control loop) will end the script. This caught me out when I mistakenly had a break in an if statement
    i.e.
    <?php 
    echo "hello";
    if (true) break;
    echo " world"; 
    ?>
    will only show "hello"
    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.
    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.

    上篇:foreach

    下篇:continue