有人可以通过示例解释循环break 2
或continue 2
PHP 中的含义吗?break
当或continue
后跟一个数字是什么意思?
4 回答
$array = array(1,2,3);
foreach ($array as $item){
if ($item == 2) {
break;
}
echo $item;
}
输出“1”,因为在 echo 能够打印“2”之前,循环永远中断了。
$array = array(1,2,3);
foreach ($array as $item){
if ($item == 2) {
continue;
}
echo $item;
}
输出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;
}
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;
}
将输出ABABAB
,因为continue 2
:每次都会通过外循环。
换句话说,continue
停止当前迭代执行但让另一个运行,同时break
完全停止整个语句。
所以我们可以说它continue
仅适用于循环,而break
可以用于其他语句,例如switch
.
一个数字表示受影响的嵌套语句的数量。
如果有 2 个嵌套循环,break
则在内部的循环中会破坏内部的循环(但是这没有什么意义,因为内部循环将在外部循环的下一次迭代中再次启动)。break 2
在内循环中会破坏两者。
这个数字只是说“要跳出多少范围”
<?php
for($i = 0; $i < 10; ++$i) {
for($j = 0; $j < 10; ++$j) {
break 2;
}
}
$i 和 $j 将为 0
引用手册:
continue 接受一个可选的数字参数,该参数告诉它应该跳到末尾的封闭循环的层数。
休息也是如此。
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;
}
}
?>
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";
}
?>
break : 打破最里面的循环(退出循环)
break 2 : 打破 2 个嵌套级别循环(从 2 个嵌套循环中退出)
continue :从使用它的地方强制循环进行下一次迭代,而不执行其余的循环代码
continue 2:强制循环进行下一次 2 次迭代,从使用它的地方开始,而不执行其余的循环代码
当我们遇到$array
值为 5时退出循环
break
$array(4,5,8);
for ($i=0 ;$i < 10 $i ++)
{
if ($array[$i]==5)
{
break;
}
}
休息(n)
当我们在 $array 中遇到值 5 时退出两个循环;
for ($i=0 ;$i < 10 $i ++)
{
for($j=0; $j <10; $j++)
{
if ($array[$i][$j]==5)
{
break 2;
}
}
}
继续
当值为 5 时将打印消息;
for($i=0; $i<10; $i++)
{
if ($array[$i] != 5)
{
continue;// will reach at the first line from here which is for($i=0;.....
}
echo 'This is five';
}
}