技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> PHP --> PHP的continue 2

PHP的continue 2

浏览:2261次  出处信息

    PHP是一种类C语言语法脚本语言, 但它有一些和C语言甚至是常见编程语言不一致的地方, 也就是PHP不符合常理的地方. 比如continue指令就是一个鲜活的例子.

    简单地把continue用在for循环中, 那么, PHP的continue和C语言的continue一样, 都是在直接跳到下一个循环, 忽略后面的代码的执行. 不过, 如果循环中包含了一个switch语句, 并且continue是放在switch里的, 那么意思就大不相同了!

    请看下面的例子:

    

[work@ideawu.net ~]$ cat a.php
2
3
4
5
[work@ideawu.net ~]$ cat t.c
#include 

int main(int argc, char **argv){
    int i;
    for(i=0; i<6; i++){
        switch(i){
            case 3:
                continue;
            default:
                break;
        }
        printf("%d\\n", i);
    }
    return 0;
}

[work@ideawu.net ~]$ ./a.out
0
1
2
4
5

    注意到了吗? PHP的指印结果里出现了数字”3″! 也就是说, continue并没有作用到for语句, 这显然和C语言以及其它的语言不一样. 再看PHP的手册, 对这种情况做了解释:

     Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.

    Note: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

    原来, 如果要达到C语言那样的效果, 必须使用”continue 2″, PHP也太二了吧! 这个陷阱如果不留意, 很容易就陷进去了. 顺便说一句, 没有goto有时极大降低效率.

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1