Forum Moderators: coopster

Message Too Old, No Replies

Using the SWITCH, CASE statement

         

daveginorge

10:44 am on Oct 3, 2008 (gmt 0)

10+ Year Member



I have read the PHP manual [no.php.net] on the SWITCH statement. I also program in other languages which brings me to the question "is it possible to use conditional case statements." eg.

switch($Cost) {
case < 10:
echo "price was less than 10 pounds";
break;
case >= 10:
echo "price was more than 10 pounds";
break;
default:
echo "An error occurred";
}

If so is there any documentation on it?

Thanks in advance.
Dave

andrewsmd

12:14 pm on Oct 3, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Unless you need it for some other reason and this was just and example you can always use if elseif. Personally I never saw the reason people hate if elseif so much it's the same thing.
If($cost < 10)
echo "price was less than 10 pounds";
elseif($cost >= 10)
echo "price was more than 10 pounds";
//there was some error
else
echo"some error";

omoutop

1:12 pm on Oct 3, 2008 (gmt 0)

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



Taken from manual:
In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

As of the 'conditional case statements', no you cant use them.
Simple... run the above script and see what errors it shows.

andrewsmd

1:24 pm on Oct 3, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes the switch is faster, but unless your comparing something big to something big or comparing 1000s of conditions, your not going to notice the extra 3ns it takes on your server to parse your code and generate HTML.

daveginorge

4:41 pm on Oct 3, 2008 (gmt 0)

10+ Year Member



Thanks for your quick replies

I know that the use of IF Statements is available for conditional evaluation but I was just wondering on the SWITCH, now I know

Thanks again.
Dave