开发者

php comparison operators 'is less than' (>) used in negative numbers is also including 0 in this switch statement?

开发者 https://www.devze.com 2023-03-29 01:09 出处:网络
This is the switch statement. Only if the variable $thumbs_number is less than -1 (e.g. -2, -3, -4, etc.), the class bad should output.

This is the switch statement. Only if the variable $thumbs_number is less than -1 (e.g. -2, -3, -4, etc.), the class bad should output.

But right now, the class bad is also being output when $thumbs_number is 0 (-1 and 1 have the right class: averag开发者_开发技巧e).

<div class="topic-like-count
    <?php // Apply style based on number of votes
        switch ($thumbs_number) {
            case ($thumbs_number < -1): echo ' bad'; break;
            case ($thumbs_number == 0):
            case ($thumbs_number == 1): echo ' average'; break;
            case ($thumbs_number == 2):
            case ($thumbs_number == 3): echo ' good'; break;
            case ($thumbs_number == 4):
            case ($thumbs_number == 5): echo ' great'; break;
            case ($thumbs_number == 6):
            case ($thumbs_number == 7): echo ' excellent'; break;
            case ($thumbs_number > 7): echo ' brilliant'; break;
        }
    ?>
  ">

What is happening?


You a misusing the switch statement.

Each case statement compares the result of the expression to the value passed to switch. So here you are comparing $thumbs_number to the result of ($thumbs_number < -1), which is either true or false.

Do this instead:

switch ($thumbs_number) {
    case 0:
    case 1:
        echo "average";
        break;
    case 2:
    case 3:
        echo "good";
        break;
    ....
    default:
        if ($thumbs_number <= -1) echo "bad";
        else if ($thumbs_number > 7) echo "brillant";
}


I faced a similar problem and I was reluctant to write a long if-else if block. Searching for an answer led me to this page.

With this technique, all you need to do is replacing

switch ($thumbs_number)

with

switch (true)

Here is my version of the code:

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号