Tutorials

PHP for beginners -Lesson 4

Sending
User Rating 4 (2 votes)

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 />
	&nbsp;&nbsp; &nbsp;case label1:<br />
	&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; This block will execute if variable=label1;<br />
	&nbsp;&nbsp; &nbsp;break;<br />
	&nbsp;&nbsp; &nbsp;case label2:<br />
	&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; This block will execute if variable=label2;<br />
	&nbsp;&nbsp; &nbsp;break;<br />
	&nbsp;&nbsp; &nbsp;case label3:<br />
	&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; This block will execute if variable=label3;<br />
	&nbsp;&nbsp; &nbsp;break;<br />
	&nbsp;&nbsp; &nbsp;default:<br />
	&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; 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.

<?php
$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) <?php
$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

<?php $dob = date("d/m");
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

Share your Thoughts