Switch doesn't work with numeric comparison cases

后端 未结 4 1799
滥情空心
滥情空心 2020-12-07 03:44

Here is my code.

$value = 0;
switch($value) {
      case ( $value <= 25 ):
            $CompScore = \'low\';
            break;
      case ($value > 25         


        
4条回答
  •  长情又很酷
    2020-12-07 04:12

    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):                 // true
                 $CompScore = 'low';
                 break;
           case ($value > 25 && $value <= 50 ): // false
                 $CompScore = 'fair';
                 break;
           case ($value > 50 && $value <= 75 ): // false
                 $CompScore = 'good';
                 break;
           case ($value >75 ):                  // false
                 $CompScore = 'excellent';
                 break;
           default:                             // if you removed the first case
                 $CompScore = 'low';            // this default case would be used
                 break;                         
     }
    

提交回复
热议问题