PHP – Switch
PHP Switch Statement: Speedy Checking
With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation!
The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.
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.
PHP Code:
$destination = "Tokyo"; echo "Traveling to $destination<br />"; switch ($destination){ case "Torino": echo "Bring an extra $500"; break; case "Bucharest": 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 "Iceland": echo "Bring a swimsuit"; break; }
Display:
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.
PHP Switch Statement: Default Case
You may have noticed the lack of a place for code when the variable doesn’t match our condition. The if statement has the else clause and the switch statement has the default case.
It’s usually a good idea to always include the default case in all your switch statements. Below is a variation of our example that will result in none of the cases being used causing our switch statement to fall back and use the default case. Note: the word case does not appear before the word default, as default is a special keyword!
PHP Code:
$destination = "New York"; 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; default: echo "Bring lots of underwear!"; break; }
Display:
Bring lots of underwear!
6,037 total views, 2 views today