Forum Moderators: coopster

Message Too Old, No Replies

Question about the switch statement.

         

nelsonm

11:18 pm on Dec 26, 2011 (gmt 0)

10+ Year Member



Just to be sure... It appears that you can't use an expression in the case clause of a switch control structure - correct?

switch(){
case <0:
break;
case >=5:
}


In my research, i have not found a reference that states that you can specify a expression in the casepart of a switch control structure. I even tried it without success.

thanks.

1888software

11:46 pm on Dec 26, 2011 (gmt 0)

10+ Year Member



The switch case statement is hardwired. You can however use the default as your catch all:

case 6:
default:

Alternatively you may NOT use a switch statement and make a series of conditional if/elseif/elseif/elseif/

penders

1:29 am on Dec 27, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You can use an expression in the case part, but not quite the way you have it in your example (as you might be able to do in other languages). The expression in the switch() part is compared for equality against the values (or result of the expression) in the case parts.

So, using your example, assuming $count is the value you are checking...

switch (true) {
case ($count < 0):
echo 'less than 0';
break;
case (($count >= 0) && ($count < 5)):
echo 'between 0 (inclusive) and 5';
break;
case ($count >= 5):
echo 'greater than or equal to 5';
}


When $count is 7 then ($count >= 5) is true, which matches the expression in the switch part, which is simply true.

However, I don't think this example takes advantage of the benefits of the switch statement. Personally I would use the if-elseif-else construct in this particular example.

nelsonm

5:17 am on Dec 27, 2011 (gmt 0)

10+ Year Member



thanks...

It's not so much a matter of taking advantage of the benefits of the switch statement, it more about being easy to read - which i find the switch construct does.

However, i've already decided to use the if-elseif-else construct.

thanks for the clarification.

penders

11:05 am on Dec 27, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It's not so much a matter of taking advantage of the benefits of the switch statement, it more about being easy to read - which i find the switch construct does.


I was including the "easy to read" ability as one of the advantages, however, I don't think it meets this criteria in this example either - but that may be a matter of opinion.