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?
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.
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.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With