我是 PHP 新手,在网上看到了下面的代码。它在 switch/case
语句中包含 continue 2
和 break
。什么意思?
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
}
最佳答案
continue 2
直接跳到结构的下一个迭代,该结构向后两层,即 foreach
。 break
(相当于 break 1
)只是结束 switch
语句。
您显示的代码中的行为是:
遍历 $elements
。如果 $element
是类型“a”并且满足 condition1
,或者如果它是类型“b”并且满足 condition2
,跳到下一个 $element
。否则,在移动到下一个 $element
之前执行一些操作。
来自 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.
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.
关于php - 继续 2 并中断 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26431066/