开发者

php switch case problem

I am trying开发者_Python百科 to say $level > -100 && $level < 100

$level  = 0;

                switch($level){                                                                                       

                case $level > -100:                                                                                   
                break;
                case $level <  100:                                                                                   
                break;
                default:
                echo '5';
                return null;                                                                                          
                }              

can you use a switch statement like this.


None of the answers presented so far have explicitly connected the spirit of the original question with a proper switch construction. So, for the record:

switch (true) {
    case (($level>-100) && ($level<100)):
        echo 'in range one';
        break;
    case (($level>200) && ($level<300)):
        echo 'in range two';
        break;
    default:
        echo 'out of range';
}

There's absolutely nothing wrong with this usage of switch.


When you say switch ($level) you're already comparing the value of $level. Each case can then only check for equality, you can't do comparisons like in your example. You'll have to use an if statement instead:

if ($level > -100 && $level < 100)
  ; // do nothing; equivalent of break in this case
else
  echo '5';

Even simpler, just negate the conditions:

if ($level <= -100 || $level >= 100)
  echo '5';


Apart of if/else, another way to do it:

switch (true)                                                                               
    case $level > -100:
        break;
    case $level <  100:
        break;
    default:
        echo '5';
        return null;
}


The other answers are both correct and incorrect at the same time. Incorrect, in that it is possible to do what you want in PHP... change switch($level) to switch(true) and your example will work. Correct, in that it's bad form and if any other programmers see that in your code they'll probably come after you with pitchforks. Its not how the switch statement is intended to be used, and wouldn't work like that in most other languages.


No you can't. Switch does only 'equals' type comparison.


No, you can't. The switch statement needs literals in the case blocks. Use an if statements instead:

if(!($level > -100 && $level < 100))
{
  echo '5';
  return null;
}


This is one of the reasons people advocating case as a superior solution to if-else are off base. I don't like the syntax or the limitations - if-ifelse-else is much more useful.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜