Jump to content

use the switch statement properly


redarrow

Recommended Posts

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";
}
*/
?>

Link to comment
https://forums.phpfreaks.com/topic/41664-use-the-switch-statement-properly/
Share on other sites

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.

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";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.