开发者

Loops within Switch statement

my switch statement has about ten outcome, but some of them need 1/2 loops to check, so i can't write them within case(condition), so i've tried using more than one default case, is this possible?

<?php

switch(true) {
case 1:
    break;
case 2:
    break;
default:
    echo "this text is never printed ??";

    while(true) {
        while(true) { // case 3
            break 3;
        }

        break;
    }

    while(true) {
        // case 4
        break 2;
    }
case 5:
    break;
default:
    while(true) {
        // ca开发者_运维问答se 6
        break 2;
    }
case 7:
    break;
}

?>

is this sort of thing possible, as my first default doesn't seem to be executing at all?!

thanks


You cannot have more than one default in a switch statement. Also, default should be at the end of of the switch after all the case statements.

What might be happening when your code is run through the PHP engine is that the parser is reading the switch statements into a hash map type data structure and each time the parser finds a default label, it's overwriting the existing entry in the hash map. So only last default label ends up in the data structure that gets used in execution.


No this isn't possible, you can't have more than one default case in a switch statement, you'll need to put additional logic into the single final case statement.

when the default case is reached it captures all conditions so later cases are not evaluated.


To answer your question - no, it is only possible to have one default and that at the end. I'm not sure whether you can place other cases after the default, but what I'm sure of is that they would never be reached...

EDIT: Also, I don't see what you're trying to do there. What's the point? Could you explain a bit? We might be able to help you accomplish what you want to do


You can have only one default in a switch. Remember that Zend is not the only thing that parses PHP, you may confuse other parsers by not putting the default case as the very last part of the switch.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜