PHP中"break"或"continue"后的数字是什么意思?

kn3*_*n3l 50 php loops continue breakpoints break

有人可以通过示例解释循环break 2continue 2PHP中的含义吗?数字何时breakcontinue后面是什么意思?

You*_*nse 85

$array = array(1,2,3);
foreach ($array as $item){
  if ($item == 2) {
    break;
  }
  echo $item;
}
Run Code Online (Sandbox Code Playgroud)

输出"1",因为在echo能够打印"2"之前,循环永远被打破.

$array = array(1,2,3);
foreach ($array as $item){
  if ($item == 2) {
    continue;
  }
  echo $item;
}
Run Code Online (Sandbox Code Playgroud)

输出,13因为第二次迭代通过

$numbers = array(1,2,3);
$letters = array("A","B","C");
foreach ($numbers as $num){
  foreach ($letters as $char){
    if ($char == "C") {
      break 2; // if this was break, o/p will be AB1AB2AB3
    }
    echo $char;
  }
  echo $num;
}
Run Code Online (Sandbox Code Playgroud)

输出AB因为break 2,这意味着两个陈述都很早就被打破了.如果这只是break,输出就是AB1AB2AB3.

$numbers = array(1,2,3);
$letters = array("A","B","C");
foreach ($numbers as $num){
  foreach ($letters as $char){
    if ($char == "C") {
      continue 2;
    }
    echo $char;
  }
  echo $num;
}
Run Code Online (Sandbox Code Playgroud)

将输出ABABAB,因为continue 2:外部循环将每次传递.

换句话说,continue停止当前迭代执行但让另一个运行,同时break完全停止整个语句.
所以我们可以continue只适用于循环,而break可以在其他语句中使用,例如switch.

数字表示受影响的嵌套语句的数量.
如果有2个嵌套循环,则break在内部循环中会破坏内部循环(但是由于内循环将在外循环的下一次迭代中再次启动,因此它没有多大意义).break 2在内循环中将打破两者.


edo*_*ian 33

这个数字只是说"跳出多少范围"

<?php
for($i = 0; $i < 10; ++$i) {
    for($j = 0; $j < 10; ++$j) {
        break 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

$ i和$ j将为0

引用手册:

continue接受一个可选的数字参数,该参数告诉它应该跳到多少级别的封闭循环到它的末尾.

同样需要休息.


Som*_*luk 9

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;
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

更多休息的例子

continue接受一个可选的数字参数,该参数告诉它应该跳到多少级别的封闭循环到它的末尾.默认值为1,因此跳到当前循环的末尾.

<?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "Middle<br />\n";
        while (1) {
            echo "Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>
Run Code Online (Sandbox Code Playgroud)

更多继续的例子