You have used the “if statement”. But sometimes, this statement can not work properly. At that time we have to use another statement. This is known as switch statement.
A quick way of verifying in PHP is switch statement
Switch statement makes your task easier for you. The way of switch statement is different to other statements. It gets a variable and then verifies it while comparing to all other variables. So, at a time it tests out many statements which is not possible in “if statement”.
An example of switch statement
Here, is an example where we have used the name of different lands. The variable which is used is $target and different cases are America, Italy, Iran, France and Arabian Sea.
echo "Traveling to $target<br />";
switch ($destination){
case "Italy":
echo “Take an Italian pizza";
break;
case "America":
echo "Take something special";
break;
case "Iran":
echo "Take a nice sweater";
break;
case "France":
echo "Take many perfumes";
break;
case "Arabian Sea":
echo "Take a swimming suit";
break;
}
Exhibit
Traveling to America
Take something special
In the above example, the value was America. By the use of switch statement, a case was searched having the value of America. When the text was displayed, the text from the case was also printed.
All the codes have “break”. It avoids the case from execution. Switch statements are exclusive in their function. if you want to become an expert then you are required a lot of practice.
Default case in Switch statement
You have to know that switch statement has default case as “if statement” contains else section. So, it will give you a good result, if you add default secton in all the switch statements. Here is an example where we have not used any case. Due to that reason, we ought to use default case. One more thing to remember is that default is a main keyword and case does not come previous to default.
echo "Traveling to $target<br />";
switch ($destination){
case "Italy":
echo “Take an Italian pizza";
break;
case "America":
echo "Take something special";
break;
case "Iran":
echo "Take a nice sweater";
break;
case "France":
echo "Take many perfumes";
break;
case "Arabian Sea":
echo "Take a swimming suit";
break;
default:
echo "Take lots of dresses!";
break;
}
Exhibit:
Traveling to London
Take lots of dresses!
Leave a Reply