Advertising


Navigation
External Links
Banner

It's the 'Switch'!


Oooo, now we're getting fancy! Now, what say we have a huge list of if statements? Is there any way to bundle them up into one evaluation? Of course! This well save you from nests of if statements and will make life a bit easier for you. This is called the Switch statement. A switch statement allows you to define a variable as being a "switch" Let's take a look at a little script I threw together to quote prices of menu items at a resturant:

    <?PHP
    $food = "Omellette";
	echo "Menu Item $food<br />";
switch ($food){
case "Fish":
echo "$12";
break;
case "Ham":
echo "$10";
break;
case "Omellette":
echo "$8";
break;
case "Coffee":
echo "$2";
break;
case "Bread":
echo "$1";
break;
default:
echo "Unknown Item!";
break;

}
    ?>



This will return "$8" The break statement defines the end of the that condition's action, if there was no break statement everything after would also be run! You see the default clause? What happens there is that if none of the other conditions are matched the default clause is executed. This is comparable to an else statement.

Page 5 of 6

Previous 1 2 3 4 5 6 Next