PHP Switch Statement
Posted by tutor | Posted in PHP Tutorial | Posted on 12-12-2009-05-2008
0
We have seen that If…elseif…else statement can be used where there are multiple conditions, but if the conditions are 20 or 30, then this number of if and elseif will look very clumsy. This may even decrease the code readability.
The other way round to solve this problem is to use the switch statement. As the name implies, it is a switch kind of construct, which switches between which code to execute, depending upon the value of switch variable.
Switch statement takes a single variable as input and then checks it against all the different cases you set up for that switch statement.
The PHP Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
- switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
First we have a single expression or a variable n, which is evaluated once. The value of the expression is then compared with the values for each case in the structure. If the expression value matches with a case value, the block of code associated with that case is executed.
At the end of each code block of every case ther is break statement, this break statement says that the condition is fulfilled so break out of the switch case. This prevents the code from running into the next case automatically.
After all the cases have been defined, we define a default case. This default case, as its name implies, is a case which is executed if the expression value matches with no other case value.
You can print a generic statement saying wrong choice or no matching values so that the user may know that a wrong input is given.
<html>
<body>
<?php
switch ($x)
{
case 1:
echo “Number 1″;
break;
case 2:
echo “Number 2″;
break;
case 3:
echo “Number 3″;
break;
default:
echo “No number between 1 and 3″;
}
?>
</body>
</html>
