• Tutorial List

PHP Switch Case Statement

Last updated May 15, 2020
PHP Switch Case Statement

PHP Switch Case Statement

The PHP Switch Case Statement is used to perform specific tasks based on specific conditions. And it is slightly similar to conditional statements.


Syntax of the Switch Statement

<?php
  switch(the_value){
      
      case value_1:
          //code to be executed if(the_value == value_1);
          break;

      case value_2:
          //code to be executed if(the_value == value_2);
          break;

      case value_3:
          //code to be executed if(the_value == value_3);
          break;

      case value_4:
          //code to be executed if(the_value == value_4);
          break;

      default:
          //code to be executed if the_value is different from all above cases;
  }
?>

  • the_value – This is the value you want to compare with the case value.
  • case value_* – If the case value matches with the “the_value“, the matched case block will be executed.
  • break – when the case value matched, and after executing the matched case code block, it will stop the code to go next case to match the value.
  • default – This block will run if no match is found.

Example of the Switch Case Statement

<?php
  $favoriteGame = 1;

  switch($favoriteGame){
      case 1:
          echo "My favorite game is Football.";
          break;

      case 2:
          echo "My favorite game is Cricketl.";
          break;

      case 3:
          echo "My favorite game is Baseball.";
          break;

      case 4:
          echo "My favorite game is Hockey.";
          break;

      default:
          echo "There hasn't my favorite game on the list.";
  }
?>
Browser Output
My favorite game is Football.

How to use switch-case with brackets?

<?php
  $favoriteGame = 1;

  switch($favoriteGame){
      case 1:{
          echo "My favorite game is Football.";
          break;
      }

      case 2:{
          echo "My favorite game is Cricketl.";
          break;
      }

      case 3:{
          echo "My favorite game is Baseball.";
          break;
      }

      case 4:{
          echo "My favorite game is Hockey.";
          break;
      }

      default:{
          echo "There hasn't my favorite game on the list.";
      }
  }
?>