Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP CASE statement not working with ZERO values

I don't understand what's happening here. Logically, it doesn't make any sense to me.

<?php
$level = 0;

switch ($level) {

  case $level > 80: $answer = 'high'; break;
  case $level > 60: $answer = 'moderate-to-high'; break;
  case $level > 40: $answer = 'moderate'; break;
  case $level > 20: $answer = 'low-to-moderate'; break;
  default: $answer = 'low'; break;
}   
echo $answer;
?>

When $level == 0, it returns "high". This doesn't make any sense to me. Can someone explain what's happening here?

like image 921
pbarney Avatar asked Nov 26 '09 00:11

pbarney


3 Answers

Change switch ($level) to switch (true) and this will work.

switch statements perform equality tests on the values in the cases. PHP is evaluating your > comparisons, so case $level > 80 becomes case false. false is considered to be equal to 0, so the first case matches.

like image 65
Phil Ross Avatar answered Sep 22 '22 14:09

Phil Ross


The quantity after the case needs to be just the value, not a boolean expression. I'm guessing that PHP is evaluating case $level > 80 as case ($level > 80) which is becoming case 0 (i.e., false, since $level is indeed NOT less than 80) and so you're matching the first case.

like image 26
James Cronen Avatar answered Sep 19 '22 14:09

James Cronen


Are you sure you can do this in php?

I just checked the manual of switch and you have to provide a distinct value.

I think if you can write it again into something like:

$levelDivTwenty = intval($level/20);
$levelDivTwenty = ($levelDivTwenty>4)?4:$levelDivTwenty;

and then case on that.

switch ($levelDivTwenty) {
  case 4: //same as $level > 80 before...
  case 3: //>60 etc...
}
like image 40
Dimitrios Mistriotis Avatar answered Sep 18 '22 14:09

Dimitrios Mistriotis