In many occasions, you may want to execute a different statement depending on which value it equals to.
If you use the If Statement,you would have to check with a nasty long block of If...ElseIf...ElseIf...Else statements.
Alternative method is to use the swtichstatement.
Syntax:
switch(expr){
case value1:
// Code to be executed if expr==value1
break;
case value2:
// Code to be executed if expr==value2
break;
...
default:
// Code to be executed if the expr is different from all values
}
<?php
$i = 1;
switch ($i) {
case 1:
echo "case 1";
break;
case 2:
echo "case 2";
break;
default:
echo "default";
break;
}
?>
Output:
case 1
Don't forget to use break statement to indicate the end of case block.
If the break is missing, it will execute the code in next case block:
switch(expr){
case value1:
// Code to be executed if expr==value1
case value2:
// Case block. Code to be executed if expr==value1 or expr==value2
break;
...
default:
// Code to be executed if the expr is different from all values
}
Example without break
<?php
$i = 1;
switch ($i) {
case 1:
echo "case 1";
case 2:
echo "case 2";
break;
default:
echo "default";
break;
}
?>
Output:
case 1case 2
<?php
$i = 1;
switch ($i) {
case 1:
case 2:
echo "case 2";
break;
default:
echo "default";
break;
}
?>
Output:
case 2