Forum Moderators: coopster

Message Too Old, No Replies

Is this valid in a switch statement?

         

peco

9:29 pm on Oct 25, 2008 (gmt 0)

10+ Year Member



If you have multiple conditions for each case, is using the double pipe for "or" valid or should you use multiple "case".

i.e. this

case "Tabby" ¦¦ "Siamese" ¦¦ "Manx":
echo "This is a cat";
break;

case "Labrador" ¦¦ "Alsatian" ¦¦ "Rottweiler":
echo "This is a dog";
break;

or should it be like this

case "Tabby":
case "Siamese":
case "Manx":
echo "This is a cat";
break;

case "Labrador":
case "Alsatian":
case "Rottweiler":
echo "This is a dog";
break;

cameraman

9:37 pm on Oct 25, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It should be multiple cases like your second version.

peco

9:41 pm on Oct 25, 2008 (gmt 0)

10+ Year Member



Thanks cameraman.

I tried the double pipe and it worked but I didn't think it was valid. I'll use the second version.

cameraman

10:02 pm on Oct 25, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmmm, interesting that it worked - I've never even tried it.
According to php.net:
The case expression may be any expression that evaluates to a simple type...

which would imply to me that your logical ORs would actually be considered valid, although they don't show any examples like that.

peco

11:44 pm on Oct 25, 2008 (gmt 0)

10+ Year Member



The reason I thought it invalid is I have never seen any examples of using OR, although as you say, it is logical. It does work though. Did you try it yet?

cameraman

1:41 am on Oct 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I tried it on my 5.2.x on windoze and the OR always gets the win, even when it isn't supposed to:
$test = "billy";
switch($test) {
case 'sam' ¦¦ 'samson':
echo "it's sam";
break;
case 'billy':
echo "it's billy";
break;
default:
echo "No match";
break;
}

I always get 'it's sam'.

peco

12:02 am on Nov 7, 2008 (gmt 0)

10+ Year Member



You are absolutely right cameraman, thanks for testing it. I only tried with one set of case statements before, which makes it appear that OR works. Testing as you did, it gives the first result for all.

Ah well, I guess we didn't make an earth shattering discovery.

jatar_k

2:49 pm on Nov 7, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



with the drop through cases above it lets you use a base functionality and extend some other cases.

I wouldn't use it extensively but it is definitely useful

I believe in 8 yrs I've used it twice

logically there may be faster or more direct ways to achieve the same thing