Switch doesn't work with numeric comparison cases

后端 未结 4 1789
滥情空心
滥情空心 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:08

    You can "smarten up" your code with a lookup array and some simple mathematics.

    Code: (Demo)

    $lookup = [
        1 => 'low',
        2 => 'fair',
        3 => 'good',
        4 => 'excellent'
    ];
    
    for ($i = -1; $i <= 101; ++$i) {
        echo "\n$i : " , $lookup[ceil($i / 25)] ?? $lookup[1];
    }
    

    By dividing the value by 25, then rounding up to the next whole number (with ceil()), you achieve the same result without a battery of condition statements. Using a lookup away not only keeps your code compact, it ensures that you aren't performing n checks on the same value AND it provides a clean separation between the process and the values.

    If you ever decide to split the groups by 20, instead of 25, you would only need to change the 25 to 20, then add a fifth lookup value in the desired location (with the appropriate key).

提交回复
热议问题