Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 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 Answer

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';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...