Use OR operator in a CASE in PHP

8

How to use the or operator in a control structure switch ?

Example

switch ($options) {

    case 1 || case 2:
        echo "Valor de opção 1 e 2";
        break;

    case 3:
        echo "Valor de opção 3";
        break;
}
    
asked by anonymous 10.04.2015 / 21:58

3 answers

8

Can not use || or any operator. If you need to do this, you must use a if structure. The switch was created for comparison of values directly and individually, it can not have expressions.

But you can get what you want in this specific case since it's fallthrough :

switch($options){
   case 1:
   case 2:
       echo "Valor de opção 1 e 2";
       break;
   case 3:
       echo "Valor de opção 3";
       break;
  }

Since cases is running in sequence, then you just put case without specifying anything inside it, so whatever is specified in some case will be executed by it. This is only broken when using break , which closes all evaluations of cases . In this construct, unlike if , closing evaluations should be done explicitly.

    
10.04.2015 / 22:03
8

To use the same behavior in different cases, you should write it this way:

switch($options) {
    //Observe que não dei um break no case 1, pois ele executará a mesma função do case2.
    case 1: 
    case 2: 
        echo "Valor de opção 1 ou 2";
        break;
    case 3:
        echo "Valor de opção 3";
        break;
    default:
        echo "operação default"; 
        break;
}
    
10.04.2015 / 22:02
4

Existing answers explain this well, but for "educational" reasons, I'll leave a way to use the control structure switch as if it were a if :

switch with OR

In order to be able to use || or OR , we have to start our control structure as Boolean and in each case make the desired comparison:

View on Ideone .

$a = 3;

switch (true) {
  case ($a == 1 || $a == 2):
        echo "variável A é 1 ou 2";
        break;

    case ($a == 3 || $a == 4):
        echo "variável A é 3 ou 4";
        break;
}

The trick here is that we are passing an expression to switch and performing comparisons with another expression.

It is an alternative method, which allows us to expand the potentiality of this control structure, although it goes against its purpose as described in documentation :

  

The statement switch is similar to a series of statements IF on the same expression .

In the example we are not doing any of this, thus making each case in if over a different expression.

The bottom line is that this is an incorrect way of dealing with the issue. We should use the control structure if for cases where we need to make use of operators, because it was designed for this purpose.

    
10.04.2015 / 23:04