๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

PHP Switch

A switch statement picks one block from a list of cases by matching a value. Each case names one value to match.

One case matches

The value 2 matches the second case. Only that line prints.

<?php
$day = 2;
switch ($day) {
  case 1:
    echo "Monday\n";
    break;
  case 2:
    echo "Tuesday\n";
    break;
  case 3:
    echo "Wednesday\n";
    break;
}

No break in the first case

This case has no break at its end. The next case runs as well, so two lines print.

<?php
$day = 2;
switch ($day) {
  case 2:
    echo "Tuesday\n";
  case 3:
    echo "Wednesday\n";
    break;
}

Default catches the rest

The value 7 matches no case here. The default case prints its line instead.

<?php
$day = 7;
switch ($day) {
  case 1:
    echo "Monday\n";
    break;
  case 2:
    echo "Tuesday\n";
    break;
  default:
    echo "Another day\n";
    break;
}

Example

<?php
$day = 6;
switch ($day) {
  case 5:
    echo "Friday\n";
    break;
  case 6:
    echo "Saturday\n";
    break;
  case 7:
    echo "Sunday\n";
    break;
  default:
    echo "Another day\n";
    break;
}

Key points

  • A switch chooses one case from a list by matching values.
  • A switch compares its value against each case with ==, the loose comparison.
  • Each case ends with a colon.
  • The break statement ends a case so the next case does not run.
  • The default case runs when no case matches the value.

In this example, the day number is 6. The switch checks the cases in order until it reaches case 6. That case prints the Saturday line. Its break then ends the switch.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A case in a switch has no break at its end. What happens after that case runs?