PHP CASE statement does not work with ZERO values

I don’t understand what is going on here. Logically, this makes no 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". It makes no sense to me. Can someone explain what is going on here?

+6
php switch-statement
source share
5 answers

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

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

+26
source share

The number after case should be just a value, not a boolean expression. I assume that PHP evaluates case $level > 80 as case ($level > 80) , which becomes case 0 (i.e. False, since $level really not less than 80), and therefore you correspond to the first case.

+5
source share

As others pointed out, you cannot use such a switch, but how to define it like this:

 <? $level = 21; $answers = array('low', 'low-to-moderate', 'moderate', 'moderate-to-high', 'high'); echo $answers[intval(($level-1)/20)]; ?> 

Note If $ level = 0 , then the expression inside intval () will be -1/20 > , which is less than -1 and therefore will be rounded to 0 .

+1
source share

This is actually not how the switch should be used. He must evaluate a specific value.

Use if / else if here, instead of complicating your life to make the switch work as one.

+1
source share

Are you sure you can do this in php?

I just checked the switch manual and you need to provide a great value.

I think if you can write it again in 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... } 
0
source share

All Articles