The SWITCH statement is an alternate of a complicated nested if structure which is used for decision making. Below we explain the IF structure.
Syntax:
switch (n)
{
case value1:
statement;
break;
case value2:
Statement;
break;
...
...
...
default:
Statement;
}
In Switch Statement we have a expression mostly a variable for example n. Below in the body of switch we have different cases. In each case we compare this variable n with each case. If this value match with any case the block of the statement in that case will be execute and then Break keyword transfer the control after the body of switch statement and prevent the code from running into the next case automatically. In the end we use a default case which means that if no one case match with our condition then the default statement will be execute.
For example :
$month=date("m");
switch ($month)
{
case 1:
echo "Month is January";
break;
case 2:
echo "Month is February";
break;
case 3:
echo "Month is March";
break;
case4:
echo "Month is April";
break;
case 5:
echo "Month is May";
break;
case6:
echo "Month is June";
break;
case 7:
echo "Month is July";
break;
case 8:
echo "Month is August";
break;
case 9:
echo "Month is September";
break;
case 10:
echo "Month is October";
break;
case 11:
echo "Month is November";
break;
default:
case 12:
echo "Month is December";
break;
default:
echo "Invalid Number Enter ?";
}
?>
In the above code first date function get the current date from system and return only month in number. next this month number is store in variable $month. This variable test in each case if this number match with any case then the statement under the body of that case will execute. For example if date return month number 8 then its match with:
case 8:
echo "Month is August";
break;
and then Break statement stop further matching the other case and control transfer out from the switch statement.
so the result is will be display
"Month is August"
Variables in PHP
PHP Concatenation
Calculation in PHP
If Statements in PHP
if ... else Statements in PHP
Nested IF Structure in PHP
PHP Comparison Operators
Switch Statement in PHP
Logical Operators In PHP
PHP Booleans
FOR Loop in PHP
While Loop In PHP
foreach Loop In PHP
Break Statement
Array In PHP
Associative Array
The Count function
Changing Case Function
Trim Function In PHP
Str_shuffle( ) function
strpos function in PHP
Explode() Function in PHP
Function
Passing Function Arguments
Server Variables
Header Function
Include Function
The require Function