That's not how switches work.
According to the manual:
The switch statement is similar to a series of IF statements on the
same expression. In many occasions, you may want to compare the same
variable (or expression) with many different values, and execute a
different piece of code depending on which value it equals to. This is
exactly what the switch statement is for.
An evaluation like
case ($x > 5):
simply equates to
case true:
or
case false:
depending on the value of $x
because ($x > 5)
is an EVALUATION, not a VALUE. Switches compare the value of the parameter to see if it equates to any of the case
s.
switch($x) {
case ($x > 5): // $x == ($x > 5)
echo "foo";
break;
case ($x <= 5): // $x == ($x <= 5)
echo "bar"
break;
default:
echo "default";
break;
}
The comparison in the above code is equivalent to
if ($x == ($x > 5)) {
echo "foo";
} elseif ($x == ($x < 5)) {
echo "bar";
} else {
echo "five";
}
which (when $x == 50
) is equivalent to
if ($x == true) {
echo "foo";
} elseif ($x == false) {
echo "bar";
} else {
echo "five";
}
which is equivalent to
if (true) { // $x == true is the same as saying "$x is truthy"
echo "foo";
} elseif (false) {
echo "bar";
} else {
echo "five";
}
IF, however, you used your switch statement as it is intended to be used (to compare the parameter to concrete values):
switch ($x) {
case 50:
echo "foo ";
case 30:
echo "bar ";
default:
echo "foo-bar";
}
and $x == 50
, your output would be
foo bar foo-bar
due to the fact that you have no break
in your cases.
Had you added the break
keyword to the end of each case, you would only execute the code for that specific case.
switch ($x) {
case 50:
echo "foo ";
break;
case 30:
echo "bar ";
break;
default:
echo "foo-bar";
break;
}
Output:
foo