leo
leo

Reputation: 17

php switch wrong response when value is zero

Whats wrong? this switch prints the second case, why?

$myvalue = 0;

switch ($myvalue)
{
    case ($myvalue >= 0 )and($myvalue <= 2 ): 
        echo "case 1";echo "<br>";
        break;
    case ($myvalue >= 3 )and($myvalue <= 12 ): 
        echo "case 2";echo "<br>";
        break;
    case ($myvalue >= 13):echo "3";
        echo "case 3";echo "<br>";
        break;
}

Upvotes: 1

Views: 52

Answers (1)

iainn
iainn

Reputation: 17417

You're switching on a value of 0, which is "falsy". So the first case that evaluates to false is the one that's running.

A switch statement compares the result of the case conditions to the value used at the top. So if you want the first true case to be the one that runs, you need to use switch (true):

$myvalue=0;

switch (true) {
    case ($myvalue >= 0 )and($myvalue <= 2 ): 
        echo "case 1";echo "<br>";
        break;
    case ($myvalue >= 3 )and($myvalue <= 12 ): 
        echo "case 2";echo "<br>";
        break;
    case ($myvalue >= 13):echo "3";
        echo "case 3";echo "<br>";
        break;
}

See https://3v4l.org/cBJa8

As mentioned in a comment, you might also want to refactor this to use && rather than and. It won't make any difference in this case, but there are some subtle changes that you might run into later.

Upvotes: 3

Related Questions