If..Else..ElseIf, Switch Statements – PHP Basics

If…Else..ElseIf Statement is used when you want to perform different conditions in a program.

If one condition is true another is also true – If Statement
If one condition is true and another is false – If..else Statement
If more than two condition is needed – If..else..elseIf Statement
Selects one of many blocks of code to be executed – Switch Statement

if..else..elseif Statement :

<!DOCTYPE html>
 <html>
 <body>

<?php
 $t = date("H");
 echo " <p> Hey There,\n </p> ";
 if ($t < "10") {
 echo "Have a good morning!";
 } elseif ($t < "20") {
 echo "Have a good day!";
 } else {
 echo "Have a good night!";
 }
 ?>

</body>
 </html>

Output :

Switch Statement :

<!DOCTYPE html>
 <html>
 <body>

<?php
 $favfood = " ";

switch ($favfood) {
 case "Spaghetti":
 echo "Your favorite food is Spaghetti!";
 break;
 case "Pasta":
 echo "Your favorite food is Pasta!";
 break;
 case "Sandwich":
 echo "Your favorite food is Sandwich!";
 break;
 default:
 echo "Your favorite food is neither Spaghetti, Pasta, nor Sandwich!";
 }
 ?>

</body>
 </html>

Output :

 

When $favfood =” “;
When $favfood = “Spaghetti”;

 

Leave a Reply

avatar
  Subscribe  
Notify of