PHP Switch

The switch statement allows us to select among different options for a value and run different pieces of code depending on which value it is set!

Syntax of switch:

switch(expression)
{
   case value1:
       //operators1;
       break;
   case value2: 
       //operators2;
       break;
   default:		 
       //default operators3;
}

The switch statement is executed line by line. In the beginning it checks the value of the expression, then controls transferred case, which value is matched the value of expression. If the value of the switch expression does not match anyone of values cases , then goes to the operator, tagged as default.

<?php
    $value = 2 ;
    switch($value) 
   {
      case 1:
          echo ("case 1");
          break;
      case 2: 
          echo ("case 2");
          break;
      case 3:
          echo ("case 3");
          break;
      default:		 
          echo ("default");
}

// ouptput case 2

?>

When the value of expression is matched cases, php continues executed all codes, until it meets the operator break.

<?php
    $value = 2 ;
    switch($value) 
   {
      case 1:
          echo ("case 1");
      case 2: 
          echo ("case 2");
      case 3:
          echo ("case 3");
}

// ouptput case 2 case 3 

?>

List of operators in case, also can be empty, he simply passes control to the next operator list of case .

<?php
    $value = 1 ;
    switch($value) 
   {
      case 1:
      case 2: 
          echo ("value > 3 and value < 0 ");
          break;
      case 3:
          echo ("case 3");
          break;
      default:		 
          echo ("default");
}

// ouptput value > 3 and value < 0

Expression in the case statement can be any expression which evaluates to a simple type, that is the type integer, or floating point type (float), or a string. Arrays or objects can not be used here as long as they are not defined to a simple type.