John
John

Reputation:

Can I use a logical "or" in a PHP switch statement case?

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

case 4 || 5:
    echo "Hilo";
    break;

Upvotes: 4

Views: 4363

Answers (5)

Musa
Musa

Reputation: 1

switch($a) {
    case 4 || 5:
        echo 'working';
        break;
}

Upvotes: -2

schnaader
schnaader

Reputation: 49719

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
}

Upvotes: 14

Marek Karbarz
Marek Karbarz

Reputation: 29304

you could just stack the cases:

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

Upvotes: 3

Rob
Rob

Reputation: 8195

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

case 4:
case 5:
    // do something
    break;

Upvotes: 3

Amir Afghani
Amir Afghani

Reputation: 38541

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

Upvotes: 4

Related Questions