PHP Switch Statement

  • With the use of the switch statement you can check for all these conditions at once.
  • the great thing is that it is actually more efficient programming to do this. A true win-win situation.
  • it takes a single variable as input and then checks it against all the different cases you set up for that switch statement.
  • The server will execute a PHP switch statement quicker than multiple “elseif”s. Also, there’s actually less code for the programmer to write.
Syntax
switch (expression)
{
case value1
code to be executed if the expression is equal to value1;
break;
case value2
code to be executed if the expression is equal to value2;
break;
case value3
code to be executed if the expression is equal to value3;
break;
default
(optional) code to be executed if none of the above conditions are true.
break;
}
Example
$destination = “Tokyo”;
echo “Traveling to $destination”;
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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *