PHP的continue 2

idea's blog 2011-02-28 23:08:16 累计浏览 3,210 次

    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有时极大降低效率.

同分类推荐文章

  1. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,699)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,566)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,818)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,718)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 13,270)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,947)
  7. Redis消息队列的若干实现方式 (累计阅读 12,535)
  8. 到底什么是MVC? (累计阅读 12,382)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 12,218)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,969)