Is it possible to use || in PHP switch?

534 views Asked by At
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

5

There are 5 answers

0
Michael Haren On BEST ANSWER

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.

0
Jed Smith On

Instead, use one of the primary advantages of switch statements:

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

    case 2:
        apple();
        break;
}
0
paxdiablo On

I think what you need is:

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

    case 2:
      apple();
    break;
}

Interestingly, I've heard that Perl is (or maybe even has, by now) introducing this syntax, something along the lines of:

if ($a == 3 || 5)

I'm not a big fan of that syntax since I've had to write lexical parsers quite a bit and believe languages should be as unambiguous as possible. But then, Perl has solved all these sorts of problems before with those hideous tail-side ifs and ors so I suspect there'll be no trouble with it :-)

0
too much php On

No, if you wrote case 3 || 5:, then you might as well just write case True:, which is certainly not what you wanted. You can however put case statements directly underneath each other:

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

        case 2:
          apple();
        break;
    }
1
bobobobo On

Yeah, I think what you've got there is equivalent to:

    <?php

    $foo = 5000 ;

    switch( $foo )
    {
      case true :   // Gzipp:  an '=='-style comparison is made
        echo 'first one' ; // between $foo and the value in the case
        break;             // so for values of $foo that are "truthy"
                           // you get this one all the time.

      case 2:
        echo 'second one';
        break;

      default:
        echo 'neither' ;
        break;
    }

    ?>