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?
You are effectively not matching numbers any more, but matching the boolean outcome.
Any positive or negative number casts to boolean
trueand only0casts tofalse, so basically for a positive or negative number you are comparingtrueto($x < 0)or($x > 0)and that gives the outcome you expect.However,
0casts tofalseand(0 == 0)istrueso you will never have a match there. And as0 < 0is alsofalse, your first statement in the switch is matched.