Minimal Basics on Switch statements
What is switch statement in php ?
Switch is a conditional statement , which perform specific action according to various condition. It is equivalent to If else strcutures.
Syntax :
switch (variable) {<br /> case label1:<br /> This block will execute if variable=label1;<br /> break;<br /> case label2:<br /> This block will execute if variable=label2;<br /> break;<br /> case label3:<br /> This block will execute if variable=label3;<br /> break;<br /> default:<br /> This block will execute if variable not matching with any label;<br /> }<br />
variable can be integer,string, character, float, double etc..
switch is similar to if..elseif..esle statement.
Note : break is required , if you missed break then it will check next case and execute default case also.
$num = 2;
switch($num){
case 1:
echo "My number is One";
break;
case 2:
echo "My number is Two";
break;
case 3:
echo "My number is Three";
break;
default :
echo "Not matching";
}
?>
Output : My number is Two
1. Checking vowel & consonant(Only for Small case letter)
$c = 'u';
switch($c){
case 'a':
echo "$c is Vowel";
break;
case 'e':
echo "$c is Vowel";
break;
case 'i':
echo "$c is Vowel";
break;
case 'o':
echo "$c is Vowel";
break;
case 'u':
echo "$c is Vowel"; break;
default:
echo "$c is Consonant ";
}
?>
Output : u is Vowel
2. Wishing birthday on current date
switch($dob){ case "10/02":
echo "Happy birthday Somnath";
break;
case "23/07":
echo "Happy birthday Santosh";
break;
case "18/08":
echo "Happy birthday Anil";
break;
case "04/09":
echo "Happy birthday Jassi";
break;
case "11/12":
echo "Happy birthday Ritesh";
break;
default: echo "No birthday party";
} ?>
if Today's date is – 23/07/2011
Output : Happy birthday Santosh