Pages

Saturday, 16 June 2012

SWITCH Statement

We use the switch statement to select one of many blocks of code to be executed.The syntax for switch statement is very much similar to that of C or C++.
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;
}
Explanation:-
The switch(n) is starting of the statement.At next line { indicates starting of body of switch(n).Please note before starting the switch statement we have to declare variable whatever we take like we have taken here n in the syntax.we use dollar sign ($) then name of variable like:- $n.

Then different cases or multiple choices are filled according to the requirement.To we use break statement to prevent the code from running into the next case automatically. The default statement is used if no match is found.
Now we take a simple example to explain above syntax. 
<?php  //PHP script starts
$d=date("D"); //variable declaration
switch ($d)     //switch statement
{                    //starting of switch
case "Mon":   //multiple statement begins
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}          //switch ends
?>        //PHP script ends




No comments:

Post a Comment