PHP Switch…Case Statements

In this tutorial you will learn how to use the switch-case statement to test or evaluate an expression with different values in PHP.

PHP If…Else Vs Switch…Case

The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.

    case label1:
        // Code to be executed if n=label1
    case label2:
        // Code to be executed if n=label2
        // Code to be executed if n is different from all labels

Consider the following example, which display a different message for each day.

  • <?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;
  • }
  • ?>

The switch-case statement differs from the if-elseif-else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once PHP finds a case statement that evaluates to true, it's not only executes the code corresponding to that case statement, but also executes all the subsequent case statements till the end of the switch block automatically.

To prevent this add a break statement to the end of each case block. The break statement tells PHP to break out of the switch-case statement block once it executes the code associated with the first true case.


Your Feedback:


We would love to hear from you! Please say something.