Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

php - Switch doesn't work with numeric comparison cases

Here is my code.

$value = 0;
switch($value) {
      case ( $value <= 25 ):
            $CompScore = 'low';
            break;
      case ($value > 25 && $value <= 50 ):
            $CompScore = 'fair';
            break;
      case ($value > 50 && $value <= 75 ):
            $CompScore = 'good';
            break;
      case ($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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

switch not working like that.

Since $value is 0 which is falsy value.

$value <= 25 is true, $value > 25 && $value <= 50 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';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...