Switch

☰ Menu Content


If you have say,  200 conditions to check. Then you will have to go through a nasty long block of If/ElseIf/ElseIf/ElseIf/... statements.

PHP Switch statement could check all 200 conditions at once,

PHP Switch Statement Example

In this example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam, Egypt, Tokyo, and the Caribbean Islands.

PHP Code:
$destination = "Tokyo";

switch ($destination)
{
     case "Las Vegas":
         echo "Prepare to lose money";
         break;
     case "Amsterdam":
         echo "Bring an open mind";
         break;
     case "Egypt":
         echo "Bring hats and umbrellas";
         break;
     case "Tokyo":
         echo "Bring lots of money";
         break;
     case "Caribbean Islands":
         echo "Bring a swimsuit";
         break;
}
Display:
Traveling to Tokyo
Bring lots of money

The value of $destination was Tokyo, so PHP search for a case with the value of "Tokyo". 

Php found it and proceeded to execute the code that existed within that segment.

Noticed how each case contains a break; at the end of its code area. This break prevents the other cases from being executed. 

Note: With no break statements then all the cases that follow Tokyo will be executed too. 

PHP Switch Statement: Default Case

If there are no matched case the switch statement has the default case as a safety net.

default case should be included in all your switch statements. 

See the examle below.

PHP Code:
$destination = "New York";

switch ($destination)
{
     case "Las Vegas":
         echo "Prepare to lose money";
         break;
     case "Amsterdam":
         echo "Bring an open mind";
         break;
     case "Egypt":
         echo "Bring hats and umbrellas.";
         break;
    case "Tokyo":
         echo "Bring lots of money";
         break;
     case "Caribbean Islands":
         echo "Bring a swimsuit";
         break;
     default:
         // execute this if there are no matched case statement
         echo "Travelling to nowhere;
         echo "I wish you luck!";
         break;

}
Display:
Traveling to nowhere
I wish you luck!

Note
For more detail please see Php Manual at http://www.php.net


Php Tutorial Content (menu)