David
David

Reputation: 4508

php switch strange anomaly

I have this code where $difference=0

switch ($difference) 
{
case 0<=$difference && $difference<300:
         return "A";
    break;
case 300<=$difference && $difference<600:
        return "B";
    break;  
}

I think that switch must return A but it returs B. Whats wrong ???

Upvotes: 0

Views: 121

Answers (3)

Brombomb
Brombomb

Reputation: 7076

In this case what is happening is $difference being equal to 0 is being interpreted as false. Thus you have switch(false). Each case is evaluated as a whole and there for case 2 actually returns false thus matching the switch statements evaluation and returning B. It also has to do with loose type checking. PHP.net

Upvotes: 0

Andre
Andre

Reputation: 3181

I'm posting this merely as informative.

Switches can be used with expressions, however this is tricky to do:

<?php
$value = 300;
$other = 1;

switch (true) {
    case $value <= 300 && $other:
        $var = 'A';
        break;

    case $value >= 300 && !$other:
        $var = 'B';
        break;

    case $value >= 300 && $other:
        $var = 'C';
        break;

    case $value > 300 && $other:
        $var = 'D';
        break;

    default:
        $var = 'FALSE';
        break;
}

echo $var;

The above code will display 'C' correctly. A combination of if/else statements is equivalent but I tend to find the switch more readable. Be sure to always include a default case whose value you can rely on (or maybe return from the function, throw an exception, etc).

You can also compare other variables, types, call functions (although not recommended), etc to match the value declared in the switch statement (in this case, true but can be an integer, string or any other base type).

Upvotes: 1

user142162
user142162

Reputation:

Switches with expressions like you are using will not be evaluated as you might think. Use an if statement instead:

if(0<=$difference && $difference<300)
{
    return "A";
}
else if(300<=$difference && $difference<600)
{
    return "B";
}

Upvotes: 1

Related Questions