views:

224

answers:

5
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

+24  A: 

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.

Michael Haren
+5  A: 

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

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

    case 2:
        apple();
        break;
}
Jed Smith
+6  A: 

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

paxdiablo
A: 

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;
    }
too much php
+1  A: 

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

    ?>
bobobobo
The `case true:` line will _not_ always be gotten. Each case value is loosely compared to the switch value; if it resolves to true the code is executed. So, if $foo is 0, or '', or anything else that loosely resolves to false, the case will be bypassed.
GZipp
Thanks Gzipp, updated.
bobobobo