You already know how to use the nested if....else control structure. You can typically convert an if/else code to a switch case code, but the latter is the preferred one. We will see later why excellent programmers will prefer the switch case. So, the switch case is typically similar to the if/else. However, if you want to compare some expression or a variable, which when having different value runs a different piece of code, depending on the value, switch case comes in handy.
Now, suppose some bank application takes in user inputs as letters, such that
B: checks for balance,
W: withdraws,
T: transfers and
any other input is invalid entry
Hands on...
<?php
$input="W"; // this is the user input and is meant to change
if($input=="W"){
echo "Withdraw";
}else if($input=="T") {
echo "transfer";
}else if($input=="B") {
echo "Show balance";
}else{//the default
echo "Invalid entry";
}
?>
Run the code and try to change he user input and observe the output
Output: Withdraw
The above code can be changed into a switch case
Syntax:
Swich (variable){
case value 1:
//to do code
break;
case value 2:
//to do code
break;
case value 3 :
//to do code
break;
.
.
.
case value n :
//to do code
break;
default:
//to do code
}
Hands on.....
$input = "B";
Switch($input){
case "B":
echo "Show balance";
break;
case "T":
echo "transfer";
break;
case "W":
echo "Withdraw";
break;
default:
echo "Invalid entry";
}
Run the code and try to change he user input and observe the output
Output: Show balance
Points to note:
- A special case is the default case. This case matches anything that wasn't matched by the other cases
- Space between case and value
- Full colon after case value and semi-colon after break statement
- Break statement to prevent the code from running into the next case automatically
Well, why switch case and not if/else?
- Code with nested if/else is messy and typically hard to maintain. Switch case has a cleaner code
- You understand about worst and best case of running a piece of code e.g. binary search. In worst cases, switch case is faster that if/else
- In switch case, test order does not matter. To speed up series of if/else tests one needs to put more likely cases first. With switch/case programmer does not need to think about this.
- The last else in if/else is similar to default in switch case, and must come at the end. With switch, default can be anywhere, wherever programmer finds it more appropriate.
- You already know the role of the break statement. But in cases want you want to run several cases at ones, normally called common code, you may omit the the break statement, and the code execution will run through till it meets a break. This is not possible with if/else.
I will appreciate if you left a comment or a question. The ext post will be a hot one. Do not miss.....
Labels: home