views:

138

answers:

4

Is it possible to use "or" or "and" in a switch case? Here's what I'm after:

case 4 || 5:
    echo "Hilo";
    break;
+3  A: 

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."

Amir Afghani
+11  A: 

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
}
schnaader
What about if i want case 4 and some other variable c =5 . Can i use AND
Mirage
DisgruntledGoat
thanks buddy , so we can use if inside case , Thats all rite
Mirage
Some people recommend against letting cases fall through, such as Douglas Crockford. They can be easy to miss when trying to debug.
alex
+3  A: 

No, I believe that will evaluate as (4 || 5) which is always true, but you could say:

case 4:
case 5:
    // do something
    break;
Rob
+3  A: 

you could just stack the cases:

switch($something) {
   case 4:
   case 5:
       //do something
       break;
}
Marek Karbarz