Switch Statement In Php
PHP Switch Statement :
In the previous lessons we covered the various elements that make up an If Statement in PHP. However, there are times when an if statement is not the most efficient way to check for certain conditions.
For example we might have a variable that stores travel destinations and you want to pack according to this destination variable. In this example you might have 20 different locations that you would have to check with a nasty long block of If/ElseIf/ElseIf/ElseIf/... statements. This doesn't sound like much fun to code, let's see if we can do something different.
Syntax :
Syntax
//Syntax :
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
FlowChart :
PHP Switch Statement Example :
In our example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam, Egypt, Tokyo, and the Caribbean Islands.
CODE/PROGRAM/EXAMPLE
<?php
PHP Code:
$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
}
?>
// O/P : Traveling to Tokyo
Bring lots of money
The value of $destination was Tokyo, so when PHP performed the switch operating on $destination in immediately did a search for a case with the value of "Tokyo". It found it and proceeded to execute the code that existed within that segment.
You might have noticed how each case contains a break; at the end of its code area. This break prevents the other cases from being executed. If the above example did not have any break statements then all the cases that follow Tokyo would have been executed as well. Use this knowledge to enhance the power of your switch statements!
The form of the switch statement is rather unique, so spend some time reviewing it before moving on.
Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.