php - 继续 2 并中断 switch 语句

标签 php switch-statement

我是 PHP 新手,在网上看到了下面的代码。它在 switch/case 语句中包含 continue 2break。什么意思?

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 直接跳到结构的下一个迭代,该结构向后两层,即 foreachbreak(相当于 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.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.

关于php - 继续 2 并中断 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26431066/

相关文章:

php - 最新访客

php - 我的创建表代码找不到问题

c++ - Switch 语句仅适用于某些情况

lua - Lua 语言中 switch 语句的替代方法是什么?

php - CakePHP 与 Oracle 兼容吗?其他框架呢?

php - php echo 中多余的空格

php - Ajax 调用在 WordPress 中无法正常工作

javascript - 如何减少 switch 语法的迭代

Java 使用给定字符串调用方法的最佳方式

javascript - Switch 语句未返回所需的值