PHP Switch case statement is an alternative for complex IF statements with a same expression. Its a best alternative for elseif statements using the same expression.
In many situations we need to compare a variable against different values and needs different operations according the values. Switch statement is coming for this requirement.
See the syntax structure of switch case statement in a PHP program
switch ($variable){
case $value1 :
Operation statements for this value1;
case $value2:
Operation statements for this value1;
case $value3:
Operation statements for this value1;
default:
Operation statements when there is no match in all the above cases;
}
Working of a switch case statement
switch statements is executed by line by line. No code will execute till the first match case found. After that it will execute all other case codes till a break statement found.Its really important to understand this behavior to avoid mistakes with this statement.
Usage of break statement in switch case
Break statement is used if we want to stop the execution of other cases when one case match with our condition.
See the difference in ouput for the following two sample programs
<?php $i=1; switch ($i) { case 0: echo " 0 "; case 1: echo " 1 "; case 2: echo " 2 "; default: echo " NO MATCH "; } ?>
Its output will be
1 2 NO MATCH
Here we can see that, after the match case found ( in this case 1 ) all other case codes also executed. We need to use the break statement to avoid this.
<?php $i=1; switch ($i) { case 0: echo " 0 "; break; case 1: echo " 1 "; break; case 2: echo " 2 "; break; default: echo " NO MATCH "; } ?>
Its output will be ;
1
Here we can see that program stops the execution of other case statements due to the break statement in matched case.
Switch case statements supports strings also. See the following sample PHP program with switch case dealing with strings.
<?php $i="PHP"; switch ($i) { case "ASP": echo " I hate ASP "; break; case "VB": echo " Its good but I dont want "; break; case "PHP": echo " I Love PHP "; break; default: echo " NOTHING "; } ?>
Its output will be :
I Love PHP
( Note : strings should be enclosed in double quotes)