Switch Statements In PHP

Switch Statements

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"