I recently got into an argument over how switch handles comparisons, and need help settling it.
If I write a switch such as:
switch ($x){
case ($x > 5):
echo "foo";
break;
case ($x < 5):
echo "bar";
break;
default:
echo "five";
break;
}
Which if statement is it equivalent to? A or B?
// A
if ($x > 5) {
echo "foo";
} elseif ($x < 5) {
echo "bar";
} else {
echo "five";
}
// B
if ($x == ($x > 5)) {
echo "foo";
} elseif ($x == ($x < 5)) {
echo "bar";
} else {
echo "five";
}
To everyone, let me clarify:
It is equivalent to
B.It is not “both”, it is not sometimes its one, sometimes it is the other, it is always
B. To understand why you sometimes see results that indicate that it might beA, you need to understand how type coercion works in PHP.If you pass in a falsey value to the “argument” of
switchand you use expressions in yourcases that result in a boolean value, they will only match if your expression evaluates toFALSE.switchis basically a hugeif/elseiftree that performs loose comparisons (==instead of===) between the value passed toswitch(the left side of the expression) and the expression in thecases (the right side).This can be proved quite nicely with a variation on your code:
And if we convert that to the two
if/elseiftrees:A:
B: