继续 2 并中断 switch 语句 [英] continue 2 and break in switch statement
问题描述
我是 PHP 新手,在网上看到了下面的代码.它在 switch/case
语句中将 continue 2
和 break
放在一起.什么意思?
foreach ( $elements as &$element ) {开关($element['type']){情况一:如果(条件 1)继续2;休息;情况二:如果(条件 2)继续2;休息;}//这里剩下的代码,在循环内但在 switch 语句外}
continue 2
直接跳到后面两层结构的下一个迭代,也就是foreach代码>.
break
(相当于 break 1
)只是结束 switch
语句.
您显示的代码中的行为是:
循环$elements
.如果 $element
的类型为a"并且满足 condition1
,或者如果它的类型为b"并且满足 condition2
,请跳到下一个 $element
.否则,在移动到下一个 $element
之前执行一些操作.
continue 接受一个可选的数字参数,它告诉它有多少它应该跳到结束的封闭循环的级别.默认的value 为 1,因此跳到当前循环的末尾.
<块引用>PHP 继续执行语句直到切换结束块,或者第一次看到 break 语句.
<块引用>
如果您在循环中有一个开关并希望继续下一个外循环的迭代,使用continue 2.
I am new to PHP and saw the code below online. It has continue 2
and break
together in switch/case
statement. What does it mean?
foreach ( $elements as &$element ) {
switch ($element['type']) {
case a :
if (condition1)
continue 2;
break;
case b :
if (condition2)
continue 2;
break;
}
// remaining code here, inside loop but outside switch statement
}
The continue 2
skips directly to the next iteration of the structure that is two levels back, which is the foreach
. The break
(equivalent to break 1
) just ends the switch
statement.
The behavior in the code you've shown is:
Loop through $elements
. If an $element
is type "a" and condition1
is met, or if it's type "b" and condition2
is met, skip to the next $element
. Otherwise, perform some action before moving to the next $element
.
From PHP.net:continue:
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.
From PHP.net:switch
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.
If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.
这篇关于继续 2 并中断 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!