First off, in your example, you assign instead of compare.
Assignment is done with one equal-sign (=
) while comparison is done with two or (rather) three, in php (===
).
A switch would maybe be slightly shorter, but not necessarily make the code any more readable or maintainable.
If ANY of your checks are true, it should print "hello world", which means that the switch would either use a lot of fall-through, which is kinda ugly (and raises warnings in a bunch of IDEs), or require you to have the echo "hello world";
in all cases, which would add an extra line for each case.
Personally, in a case like this, I would use an array with the values to check for, then use the in_array
function in the if statement.
Something like:
$array = ['A', 'B', 'C']; // and so on.
if(in_array($val, $array)) {
echo "hello world";
}
Edit:
Also worth noting, about switches, is that a switch does no typecheck when it compares.
That is, when a switch compares it uses ==
not ===
.