从开关'断开',然后在循环中'继续'

时间:2011-11-20 22:55:03

标签: php control-structure

是否可以从开关断开然后继续循环?

例如:

$numbers= array(1,2,3,4,5,6,7,8,9,0);
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g');

foreach($letters as $letter) {
    foreach($numbers as $number) {
        switch($letter) {
           case 'd':
               // So here I want to 'break;' out of the switch, 'break;' out of the
               // $numbers loop, and then 'continue;' in the $letters loop.
               break;
        }
    }

    // Stuff that should be done if the 'letter' is not 'd'.

}

可以这样做,语法是什么?

3 个答案:

答案 0 :(得分:15)

您想使用break n

break 2;

澄清之后,看起来像你想要continue 2;

答案 1 :(得分:8)

而不是break,请使用continue 2

答案 2 :(得分:5)

我知道这是一个严肃的死灵,但是......当我从谷歌来到这里时,我认为我会让其他人感到困惑。

如果他意味着从交换机中断开并且只是结束数字的循环,那么break 2;就可以了。 continue 2;只会继续数字的循环,并且每次只需continue'来迭代它。

因此,正确的答案应该是continue 3;

继续a comment in the docs继续基本上到达结构的末尾,对于那个切换(感觉和break一样),for循环它将在下一次迭代中获取。

请参阅:http://codepad.viper-7.com/dGPpeZ

上述案例中的例子:

<?php
    echo "Hello, World!<pre>";

$numbers= array(1,2,3,4,5,6,7,8,9,0);
$letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');

$i = 0;
foreach($letters as $letter) {
    ++$i;
    echo $letter . PHP_EOL;
    foreach($numbers as $number) {
        ++$i;
        switch($letter) {
           case 'd':
               // So here I want to 'break;' out of the switch, 'break;' out of the
               // $numbers loop, and then 'continue;' in the $letters loop.
              continue 3; // go to the end of this switch, numbers loop iteration, letters loop iteration
            break;
           case 'f':
            continue 2; // skip to the end of the switch control AND the current iteration of the number's loop, but still process the letter's loop
            break;
           case 'h':
            // would be more appropriate to break the number's loop
            break 2;

        }
        // Still in the number's loop
        echo " $number ";
    }


    // Stuff that should be done if the 'letter' is not 'd'.
    echo " $i " . PHP_EOL;

}

结果:

Hello, World!
a
 1  2  3  4  5  6  7  8  9  0  11 
b
 1  2  3  4  5  6  7  8  9  0  22 
c
 1  2  3  4  5  6  7  8  9  0  33 
d
e
 1  2  3  4  5  6  7  8  9  0  46 
f
 57 
g
 1  2  3  4  5  6  7  8  9  0  68 
h
 70 
i
 1  2  3  4  5  6  7  8  9  0  81 

continue 2;不仅处理字母d的字母循环,而且甚至处理数字循环的其余部分(注意$i在f之后递增并打印)。 (这可能是也可能不是......)

希望能帮助其他人先在这里结束。