Mastering the Switch Statement in PHP: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-18 09:14:34   5493  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

If you want to select one of many blocks of code to be executed, use the Switch statement.

The switch statement is used to avoid long blocks of if..elseif..else code.



switch (expression){
   case label1:
      code to be executed if expression = label1;
      break;  
   
   case label2:
      code to be executed if expression = label2;
      break;
      default:
   
   code to be executed
   if expression is different 
   from both label1 and label2;
}


Syntax:



<?php
$today = date("D");
switch($today){
    case "Mon":
        echo "Today is Monday. Clean your house.";
        break;
    case "Tue":
        echo "Today is Tuesday. Buy some food.";
        break;
    case "Wed":
        echo "Today is Wednesday. Visit a doctor.";
        break;
    case "Thu":
        echo "Today is Thursday. Repair your car.";
        break;
    case "Fri":
        echo "Today is Friday. Party tonight.";
        break;
    case "Sat":
        echo "Today is Saturday. Its movie time.";
        break;
    case "Sun":
        echo "Today is Sunday. Do some rest.";
        break;
    default:
        echo "No information available for that day.";
        break;
}
?>



Output:

If you will rum the above code, you will get the following output.



Today is Monday. Clean your house.