Use OR operator in a PHP CASE

Asked

Viewed 1,001 times

10

How to use the operator or 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;
}

3 answers

9


It is not possible to use the || or any operator. If you need to do this, you must use a if. The switch was created to compare values directly and individually, it cannot have expressions.

But can you get what you want in this particular case since it is 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;
}

I put in the Github for future reference.

How the execution of cases are occurring in sequence, so just put a case without specifying anything within it, than what is specified in any case later will be executed by it. This is only broken when using the break, which closes all assessments of cases. In this construction, unlike the if, close the assessments should be made explicitly.

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;
}

5

The existing answers explain this subject well, but for "educational" questions, I will leave a way to use the control structure switch as if of a if were it:

switch with OR

So we can use a || or OR, we have to start our control structure as boolean and in each case make the intended comparison:

See on the 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’re passing an expression to the switch and to make comparisons with another expression.

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

The instruction switch is similar to a number of instructions IF on the same expression.

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

The conclusion 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, as it has been designed for this purpose.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.