Marcio Mazzucato
Marcio Mazzucato

Reputation: 9305

Is it possible to use a switch statement with expressions as cases?

Using if and elseif, it is possible to easily perform the comparison below, but for learning purposes I am analyzing if it is possible to have the same functionality using switch.

If $x receives a positive or negative value, I get the right output, but if $x receives 0 (zero), I get the output 'Lower', but the right output should be 'Equal'.

Here is the code:

$x = 0;

switch($x)
{
    case ($x < 0):
        echo 'Lower';
        break;

    case ($x == 0):
        echo 'Equal';
        break;

    case ($x > 0):
        echo 'Bigger';
        break;
    default:
        echo 'Not found';
}

Is it possible to use a switch statement with expressions as cases?

Upvotes: 0

Views: 1429

Answers (3)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 2090

You are comparing if the $x is equal to test results, when $x = 0, the boolean value of $x is false. If it is different from 0, it is true. That's why you will always fall to the first test that returns false.

Try this instead :

$x = 0;

switch($x)
{

case 0:
    echo 'Equal';
    break;

case ($x < 0):
    echo 'Lower';
    break;

case ($x > 0):
    echo 'Bigger';
    break;

default:
    echo 'Not found';

}

I also read in the comments that you want to know if it possible to use sentences in each case of the switch. Yes it is possible :

$x = 0;

switch($x)
{

case ($x < 0):
    echo 'Lower';
    break;

case ($x > 0):
    echo 'Bigger';
    break;

case ($x <> 0):
    echo 'Equal';
    break;

default:
    echo 'Not found';

}

($x <> 0) will return false when $x = 0 and it will echo "Equal"

Upvotes: 0

jeroen
jeroen

Reputation: 91744

You are effectively not matching numbers any more, but matching the boolean outcome.

Any positive or negative number casts to boolean true and only 0 casts to false, so basically for a positive or negative number you are comparing true to ($x < 0) or ($x > 0) and that gives the outcome you expect.

However, 0 casts to false and (0 == 0) is true so you will never have a match there. And as 0 < 0 is also false, your first statement in the switch is matched.

Upvotes: 1

Silviu-Marian
Silviu-Marian

Reputation: 10907

switch($x) replace it with switch(true)

Upvotes: 4

Related Questions