Switch doesn't work with numeric comparison cases

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

Here is my code.

$value = 0; switch($value) {       case ( $value  25 && $value  50 && $value 75 ):             $CompScore = 'excellent';             break;       default:             $CompScore = 'low';             break; }  echo $CompScore; 

When the value is 0, $compScore is fair. Why it is not showing low? I don't understand why.

回答1:

The value you pass into a switch statement is basically what the switch statement looks for an evaluated match for, going from top to bottom down the list of cases until it finds one it is equal to (loose comparison), e.g. true == true.

In your example, your comparisons are evaluated as booleans (true or false) - your variable $value is set to zero, which is equal to false, but not identical (strict comparison) to false. For example:

(0 == false)    // true (0 === false)   // false (1 == false)    // false (1 === false)   // false (1 == true)     // true (1 === true)    // false (true === true) // true 

So by using a boolean true as your switch value, you can do this to have numeric comparison inside the statement, where each comparison will evaluate to either true or false to match/not match the original true value (boolean - boolean comparison).

switch(true) {        case ($value  25 && $value  50 && $value 75 ):                  // false              $CompScore = 'excellent';              break;        default:                             // if you removed the first case              $CompScore = 'low';            // this default case would be used              break;                           } 


回答2:

switch not working like that.

Since $value is 0 which is falsy value.

$value is true, $value > 25 && $value is false, so $CompScore will be 'fair'.

For you code, use an if elseif else flow will be more readable.

You could rewrite your code like below:

// from excellent to low if ($value > 75) {   $CompScore = 'excellent'; } else if ($value > 50) {   $CompScore = 'good'; } else if ($value > 25) {   $CompScore = 'fair'; } else {   $CompScore = 'low'; } 


回答3:

The problem is, you use your switch in a particular way.

You are saying :

$value = 0; Switch ($value){     case ($value 

This finally compares $value

($value true == 0 

Which is wrong because true != 0

A way to do what you want this way is simply to replace switch($value) with switch(true) so the interpreter will actually compare check if your case statements are true.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!