“中断"后的数字是什么意思?或“继续"在PHP中? [英] What is meant by a number after "break" or "continue" in PHP?

查看:176
本文介绍了“中断"后的数字是什么意思?或“继续"在PHP中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以举例说明在PHP中循环break 2continue 2是什么意思吗? breakcontinue后跟数字是什么意思?

Could someone please explain, with examples, what is meant by loop break 2 or continue 2 in PHP? What does it mean when break or continue is followed by a number?

推荐答案

$array = array(1,2,3);
foreach ($array as $item){
  if ($item == 2) {
    break;
  }
  echo $item;
}

之所以输出"1",是因为在回声能够打印"2"之前,循环永远被中断.

outputs "1" because the loop was broken forever, before echo was able to print "2".

$array = array(1,2,3);
foreach ($array as $item){
  if ($item == 2) {
    continue;
  }
  echo $item;
}

之所以输出13,是因为第二次迭代已通过

outputs 13 because the second iteration was passed

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

由于break 2而输出AB,这意味着两个语句都在很早就被破坏了.如果只是break,则输出应为AB1AB2AB3.

outputs AB because of break 2, which means that both statements was broken quite early. If this was just break, the output would have been 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;
}

由于continue 2

将输出ABABAB:每次都将通过外部循环.

will output ABABAB, because of continue 2: the outer loop will be passed every time.

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

In other words, continue stops the current iteration execution but lets another to run, while break stops the whole statement completely.
So we can ell that continue is applicable for the loops only, whereas break can be used in other statements, such as switch.

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

A number represents the number of nested statements affected.
if there are 2 nested loops, break in the inner one will break inner one (however it makes very little sense as the inner loop will be launched again in the next iteration of the outer loop). break 2 in the inner loop will break both.

这篇关于“中断"后的数字是什么意思?或“继续"在PHP中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆