views:

262

answers:

5

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?

+6  A: 

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.

Tenner
+17  A: 

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.

Phil Ross
This makes so much sense to me now. I had a fundamental misunderstanding in the way switch works. Thanks for the education!
pbarney
@pbamey, yup, good answer, I agree, so accept it and give Phil his due.
Don
I'm not sure if this would be the recommended approach of using a switch statement though, I wouldn't say it reads very well.
Erik van Brakel
+1  A: 

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...
}
dimitris mistriotis
A: 
Maiku Mori
that's an interesting approach
pbarney
A: 

This isn't really how switch is intended to be used. It's to evaluate for a specific value.

Use an If/else if here, instead of complicating your life to make a switch work like one.

mabwi