Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 960
Ali Avatar asked Nov 01 '09 23:11

Ali


2 Answers

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.

like image 66
Michael Haren Avatar answered Nov 12 '22 22:11

Michael Haren


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 :-)

like image 6
paxdiablo Avatar answered Nov 12 '22 20:11

paxdiablo