PHP Programing language

adplus-dvertising
PHP Switch Statement
Previous Home Next

If you have many variables that stores travel destinations and you want to pack according to this destination variable. And in this program you might have 20 different locations that you would have to check with a very 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.

Use of PHP Switch Statement

In this PHP Programming 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 Switch statement working it's 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.

Example:

In our example the single variable will be $destination and the cases will be: Tokyo, New Delhi, Japan, America, and the China.

PHP Code:

<?php
$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination)
	{
case "NewDelhi":
echo "Bring an extra $500";
break;
case " Japan":
echo "Bring an open mind";
break;
case " America":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "China":
echo "Bring a swimsuit";
break;
    }
?>

Output

Traveling to Tokyo
Bring lots of money
Previous Home Next