Control Structures


switch

The switch statement is similar to a series of if statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. A special case is the default case. This case matches anything that wasn't matched by the other cases.

Syntax Description
switch(expr)
{
  case val1:
    stmt1;
    break;
  case val2:
    stmt2;
    break;
  default:
    stmt3;
    break;
}
1) compare val1 and expr1 if they are the same
2) execute stmt1 and exit switch if val1 is the same with expr
3) compare val2 and expr1 if they are the same
4) execute stmt2 and exit switch if val2 is the same with expr
5) execute stmt3 if neither val1 nor val2 is the same with expr
<?php
  $var = 1;
  switch($var)
  {
    case 1:
      echo "var is 1";
      break;
    case 2:
      echo "var is 2";
      break;
    default:
      echo "Error";
      break;
  }
?>
[result]  
var is 1
  • Example of default
    default case can be omitted in switch statement.
<?php
  $var = 1;
  switch($var)
  {
    case 1:
      echo "var is 1";
      break;
    case 2:
      echo "var is 2";
      break;
  }
?>
[result]  
var is 1

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

  • case statement without break
<?php
  $var = 1;
  switch($var)
  {
    case 1:
      echo "3";
    case 2:
      echo "3";
    case 3:
      echo "3";
      break;
    case 4:
      echo "4";
  }
?>
[result]  
333

※ You cannot use semicolon (;) behind the case statement instead of colon (:).