Reputation: 267077
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
Upvotes: 5
Views: 537
Reputation: 881583
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 if
s and or
s so I suspect there'll be no trouble with it :-)
Upvotes: 6
Reputation: 67244
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; } ?>
Upvotes: 1
Reputation: 91028
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; }
Upvotes: 0
Reputation: 15944
Instead, use one of the primary advantages of switch
statements:
switch($foo) {
case 3:
case 5:
bar();
break;
case 2:
apple();
break;
}
Upvotes: 5
Reputation: 108276
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.
Upvotes: 24