redarrow Posted March 7, 2007 Share Posted March 7, 2007 How do you use the swich statement properly, i think i got the syntex idear correctly but never needed it before. So what is it good for, all i see in many scripts is the switch being used to change a page background, or links what else do we need it for as what i can find out it a glorryfied if statement? <?php /* // a number set to a switch. $num=300; switch($num){ case(200); echo "hello case 1"; break; case(300); defult; echo" hello case 2"; } */ /* //a name set to a switch. $name="lucy"; switch($name){ case(john); echo "case 1"; break; case(petter); echo "case 2"; case(lucy); default; echo "case 3"; } */ /* //maths with switch. $math=2*30; switch($math){ case(10); echo "correct result is 10"; break; case(20); echo"correct result is 20"; break; case(30); default; echo" correct result 30"; } */ ?> Quote Link to comment https://forums.phpfreaks.com/topic/41664-use-the-switch-statement-properly/ Share on other sites More sharing options...
Ninjakreborn Posted March 7, 2007 Share Posted March 7, 2007 If you ever have to take 1 word, and match it up against multiple things then it 1. Saves space 2. Saves resources (it's faster) 3. Looks neater 4. It's easier to block up sections of it, to do something specific with each thing Compare 350 lines of if (here) { }elseif (here1) { }elseif (here2) { }elseif (here3) { }elseif (here4) { } 200 lines of that compared to switch "here" case "here1": // do stuff case "here2": // do stuff I don't feel like typing anymore, but hopefully you get the point. I have heard before some slight security issues with the "way" switch statements are used. There are a few situations in which they can be exploited when used, I saw some posts on here about that awhile back, but I don't remember what it was. Quote Link to comment https://forums.phpfreaks.com/topic/41664-use-the-switch-statement-properly/#findComment-201896 Share on other sites More sharing options...
Barand Posted March 7, 2007 Share Posted March 7, 2007 The semi-colons at the end of your "case (xxx);" lines should be colons. Also you don't need the ()s <?php $num=300; switch ($num) { case 200: echo "hello case 1"; break; case 300: echo "hello case 2"; break; default: echo "hello case 3"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/41664-use-the-switch-statement-properly/#findComment-201944 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.