PHP for beginners -Lesson 4

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 :

[php]switch (variable) {
    case label1:
        This block will execute if variable=label1;
    break;
    case label2:
        This block will execute if variable=label2;
    break;
    case label3:
        This block will execute if variable=label3;
    break;
    default:
        This block will execute if variable not matching with any label;
}
[/php]
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

4 thoughts on “PHP for beginners -Lesson 4

Leave a Reply to santoshCancel reply

Discover more from AlienCoders

Subscribe now to keep reading and get access to the full archive.

Continue reading