Introduction
If a program needs a series of if statements that perform different process for vaarying value of an expression, it may get very clumsy with each if statement having its own set of curly brackets. This is where using swtich-case construct can make the program compact and readable. With switch construct, it is possible to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to.
Syntax
switch (expr) { case val1: code to be executed if expr=val1; break; case val2: code to be executed if expr=val2; break; ... ... default: code to be executed if expr is not equal to any of above values; }
It is important to give break statement after each case block in order to void program flow falling through the rest of the cases.
In following example, user is asked to input two numbers and a number for type of arithmetic operation 1/2/3/4 for add/subtract/multiply/divide
Example
<?php $first=(int)readline("enter a number"); $second=(int)readline("enter another number"); $x=readline("enter 1/2/3/4 for add/subtract/multiply/divide"); $result=0; switch($x){ case 1: echo $first+$second; break; case 2: echo $first-$second; break; case 3: echo $first*$second; break; case 4: echo $first/$second; break; default: echo "Incorrect input"; } ?>
Output
This will produce following result −
Incorrect input
The default keyword is used to specify block of statements to be executed if switch expression doesn't match specific cases
If a particular case block is empty, it simply passes the flow to next case.
Example
<?php $x=(int)readline("enter a number"); switch($x){ case 1: case 2: echo "x is less than 3"; break; case 3: echo "x is equal to 3"; break; case 4: echo "x is greater than 3";break; default: echo "x is beyound 1 to 4"; } ?>
Output
This will produce following result −
x is beyound 1 to 4
It is possible to use string values to be compared with switch expression
Example
<?php $x=readline("enter a something.."); switch($x){ case "India": echo "you entered India"; break; case "USA": echo "You typed USA"; break; case "Mumbai": echo "you entered Mumbai";break; default: echo "you entered something else"; } ?>
Output
This will produce following result −
you entered something else