2011-03-01

PHP的continue 2

Views: 24057 | 4 Comments

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

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

请看下面的例子:

[work@ideawu.net ~]$ cat a.php
<?php
for($i=0; $i<6; $i++){
    switch($i){
    case 3:
        continue;
    default:
        break;
    }
    echo $i . "\n";
}

[work@ideawu.net ~]$ php a.php
0
1
2
3
4
5
[work@ideawu.net ~]$ cat t.c
#include <stdio.h>

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

Related posts:

  1. PHP 解码 C 字符串
  2. C/C++ 语言 switch-case 后面的花括号
  3. 一种有趣的编程模型
  4. LevelDB Seek() 特别慢的场景
  5. Redis 导数据的 PHP 脚本
Posted by ideawu at 2011-03-01 13:52:12

4 Responses to "PHP的continue 2"

Leave a Comment