开发者

PHP CASE statement not working with ZERO values

I don't understand what's happening 开发者_JS百科here. Logically, it doesn't make any sense to me.

<?php
$level = 0;

switch ($level) {

  case $level > 80: $answer = 'high'; break;
  case $level > 60: $answer = 'moderate-to-high'; break;
  case $level > 40: $answer = 'moderate'; break;
  case $level > 20: $answer = 'low-to-moderate'; break;
  default: $answer = 'low'; break;
}   
echo $answer;
?>

When $level == 0, it returns "high". This doesn't make any sense to me. Can someone explain what's happening here?


Change switch ($level) to switch (true) and this will work.

switch statements perform equality tests on the values in the cases. PHP is evaluating your > comparisons, so case $level > 80 becomes case false. false is considered to be equal to 0, so the first case matches.


The quantity after the case needs to be just the value, not a boolean expression. I'm guessing that PHP is evaluating case $level > 80 as case ($level > 80) which is becoming case 0 (i.e., false, since $level is indeed NOT less than 80) and so you're matching the first case.


Are you sure you can do this in php?

I just checked the manual of switch and you have to provide a distinct value.

I think if you can write it again into something like:

$levelDivTwenty = intval($level/20);
$levelDivTwenty = ($levelDivTwenty>4)?4:$levelDivTwenty;

and then case on that.

switch ($levelDivTwenty) {
  case 4: //same as $level > 80 before...
  case 3: //>60 etc...
}


As others have pointed out you can't use switch like that, but how about defining it like this:

<?
$level = 21;
$answers = array('low', 'low-to-moderate',
                 'moderate', 'moderate-to-high', 'high');

echo $answers[intval(($level-1)/20)];
?>

Note: If $level = 0, then expression inside intval() will be -1/20, which is less then -1 and therefore will be rounded to 0.


This isn't really how switch is intended to be used. It's to evaluate for a specific value.

Use an If/else if here, instead of complicating your life to make a switch work like one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜