Is it possible to use "or" or "and" in a switch case? Here's what I'm after:
case 4 || 5:
echo "Hilo";
break;
Is it possible to use "or" or "and" in a switch case? Here's what I'm after:
case 4 || 5:
echo "Hilo";
break;
The way you achieve this effectively is :
CASE 4 :
CASE 5 :
echo "Hilo";
break;
It's called a switch statement with fall through. From Wikipedia :
"In C and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n=2, the fourth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution continues through the next 3 case statements and to the next line, which outputs "n is a prime number.". The break line after this causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message."
No, but you can do this:
case 4:
case 5:
echo "Hilo";
break;
See the PHP manual.
EDIT: About the AND case: switch only checks one variable, so this won't work, in this case you can do this:
switch ($a) {
case 4:
if ($b == 5) {
echo "Hilo";
}
break;
// Other cases here
}
No, I believe that will evaluate as (4 || 5) which is always true, but you could say:
case 4:
case 5:
// do something
break;
you could just stack the cases:
switch($something) {
case 4:
case 5:
//do something
break;
}