PHP Switch Statement
PHP switch statement is a variant of if-else statement. switch statement is often used when you need to compare a variable against different values. Based on the value of the variable, you can execute different specific code block. Here is the form of switch statement.
<?php
switch(variable){
case value1: // code block 1
break;
case value2: // code block 2
break;
...
default: // code block n
break;
}
?>
After the switch keyword, you put a variable to check. Following that are different cases with different values in case statements. Following by each case is a code block to be executed if the value of variable is satisfied. After each case statement, you put a break statement to end the code block. The code block of default statement is only executed if the value of the variable does not meet any value in case statements above.
It is very important to understand that switch statement is executed statement by statement therefore the order of each case is very important. If the value of variable found in a case, PHP will execute code block after that until the break statement reach. Here is examples of using switch statement.
<?php
$x = 1;
switch($x){
case 0: echo "x is equal zero";
break;
case 1: echo "x is equal 1";
break;
case 2: echo "x is equal 2";
break;
}
?>
In PHP switch statement accept string type of variable to compare.
<?php
$lang = "PHP";
switch($lang){
case "PHP": echo "PHP is cool";
break;
case "JSP": echo "JSP is cool too";
break;
default: echo "What kind of programming language?";
break;
}
?>
There are some cases you want to execute a specific code block with the variable is one of multiple specific values. You can use switch statement to do so. Here is an example:
<?php
$tech = "PHP";
switch($tech){
case "PHP":
case "JSP":
case "ASP.NET":
echo "You have a good choice";
break;
default:
echo "What kind of technology you use?";
}
?>