phpswitch-statementfall-through

Is it possible to use || in PHP switch?


switch ($foo)
    {
        case 3 || 5:
           bar();
        break;

        case 2:
          apple();
        break;
    }

In the above code, is the first switch statement valid? I want it to call the function bar() if the value of $foo is either 3 or 5


Solution

  • You should take advantage of the fall through of switch statements:

    switch ($foo)
        {
            case 3:
            case 5:
               bar();
            break;
    
            case 2:
              apple();
            break;
        }
    

    The PHP man page has some examples just like this.