The Switch Construct |
| Written by phpecho.com | |||
The switch construct is a specific kind of branching. It is used when branching is multiway - that is different routes need to be taken on various values of an expression. Consider the code below: if ($color == "red"){
// do operations for red color
} else if ($color == "blue"){
// do operations for blue color
} else if ($color == "black"){
// do operations for black color
} else {
// do operations for all other colors
}
The above if else-if construct checks the value of an expression ($color) and performs operations based on the value. So, if the color is red, a particular set of operations are performed and if the color is blue a different set of operations will be executed. The above logic can be expressed using the switch construct. The switch construct is more intuitive and easier to understand. The general structure for a switch construct is as follows: switch (expression){
case value 1:
// statements
break;
case value 2:
// statements
break;
...
...
default:
//statements
}
The expression in the first line of the structure is the criteria based on which the multiway branching will be executed. Each case statement handles an unique value of the expression. The default case handles the value which is not specified in any of the case operators. Our original example expressed as a case construct would something like this: switch ($color){
case "red":
// do operations for red color
break;
case "blue":
// do operations for blue color
break;
case "black":
// do operations for black color
break;
default:
// do operations for all other colors
}
When we use switch constructs, a couple of points must be kept in mind. One, the switch construct is executed sequentially. This means that the PHP compiler will execute the first case and then the second and so on. So, if the first case is satisfied then it will execute. If you provide the default case in the beginning, then it will execute irrespective of the value of the expression. Secondly, note the use of the break statement. If this is not used, then each case statement will get executed. If the condition is satisfied then the corresponding logic will also be executed. The most common problem faced is when the break is missed and the default statement gets executed additionally along with the particular piece of code.
|