IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

PHP的continue 2

idea's blog 2011-02-28 23:08:16 累计浏览 3,071 次
本机暂存

    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. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

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