PHP switch: How case, break, and default Work

PHP switch compares one value with several case labels and starts executing at the first match. break exits the block. When no case matches, PHP runs default if present.

Basic syntax and default

The PHP switch documentation describes how cases are checked in order. This example uses break after each case body to run only one branch. You can omit default if nothing should happen when no case matches.

Save the code as example.php and run php example.php in a terminal. Replace the file with each later example before running it.

<?php
$value = 2;

switch ($value) {
    case 1:
        echo "A\n";
        break;
    case 2:
        echo "B\n";
        break;
    case 3:
        echo "C\n";
        break;
    default:
        echo "Z\n";
}

The example prints B. Change $value to 1, 3, or 9 to get A, C, or Z, respectively.

What happens when break is missing?

If a matched case does not reach break, PHP continues into the next case body without checking its label again. This behavior is called fall-through.

<?php
$value = 2;

switch ($value) {
    case 2:
        echo "B\n";
    case 3:
        echo "C\n";
        break;
    default:
        echo "Z\n";
}

The example matches 2 and prints B. It then prints C from the body below case 3 and exits. Add break; after printing B to get just that one line.

Share one block between several cases

Stack case labels with no code between them whenever several values should trigger exactly the same work.

<?php
$format = 'tsv';

switch ($format) {
    case 'csv':
    case 'tsv':
        echo "text\n";
        break;
    default:
        echo "unknown\n";
}

Both csv and tsv print text. Set the format to json to see unknown.

Use a colon and endswitch

In the alternative PHP syntax, open the block with a colon and close it with endswitch;. Cases and breaks work as before. This example prints grid.

<?php
$view = 'grid';
switch ($view):
    case 'grid':
        echo "grid\n";
        break;
    default:
        echo "list\n";
endswitch;

Compare both value and type

switch uses loose comparison, like ==, so string '2' can match integer 2. PHP 8’s match expression uses strict comparison, like ===, and produces a value.

<?php
$value = '2';

switch ($value) {
    case 2:
        echo "B\n";
        break;
    default:
        echo "Z\n";
}

$result = match ($value) {
    2 => 'B',
    default => 'Z',
};
echo $result, "\n";

The first line is B and the second is Z. Change $value to integer 2 to get B on both lines.

Use switch for statements grouped around the same value, match for choosing a result with strict comparison, and if with elseif for ranges or unrelated conditions.