The Case Construct

The case construct is part of the switch operator and allows organizing program branching depending on the value of a variable. Each case checks if the variable value matches its condition and executes the code if a match is found.

Syntax

phpswitch ($variable) {
  case value1:
    // code to execute
    break;
  case value2:
    // code to execute
    break;
  default:
    // default code
}

Example

A simple example of using the case construct to check a numeric value:

php<?php
  $num = 2;
  switch ($num) {
    case 1:
      echo 'One';
      break;
    case 2:
      echo 'Two';
      break;
    default:
      echo 'Other number';
  }
?>

Code execution result:

php'Two'

Example

Using multiple case for one code block:

php<?php
  $char = 'b';
  switch ($char) {
    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
      echo 'Vowel';
      break;
    default:
      echo 'Consonant';
  }
?>

Code execution result:

php'Consonant'

Example

Using case with strings:

php<?php
  $day = 'Monday';
  
  switch ($day) {
    case 'Monday':
      echo 'First day of week';
      break;
    case 'Friday':
      echo 'Last working day';
      break;
    default:
      echo 'Regular day';
  }
?>

Code execution result:

php'First day of week'

See Also

  • the if operator,
    which executes code when a condition is met
  • the while operator,
    which creates a loop with a condition