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
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.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With