← Back to PHP Course | Chapter 4: Control Flow | Lesson 7 of 14

PHP switch Statement

Basic switch Statement

switch compares one variable against a list of fixed candidate values, which reads more cleanly than an equivalent elseif ladder once you're checking more than two or three specific values against the same variable.

Example: Basic switch Statement

php
<?php
$day = "Tuesday";
switch ($day) {
    case "Monday":
        echo "Start of week";
        break;
    case "Tuesday":
        echo "Second day";
        break;
}
?>

The Importance of break

Without an explicit break, execution 'falls through' into the next case's code after a match is found, running it too even though its own condition was never checked — a frequent source of bugs, and the main reason break is treated as mandatory at the end of nearly every case.

Example: The Importance of break

php
<?php
$day = "Monday";
switch ($day) {
    case "Monday":
        echo "Monday\n";
    case "Tuesday":
        echo "Tuesday (falls through!)\n";
        break;
}
?>

Default Switch Case

default runs when the tested value doesn't match any listed case — functionally the same role else plays at the end of an elseif ladder, catching whatever wasn't explicitly handled above it.

Example: Default Switch Case

php
<?php
$fruit = "mango";
switch ($fruit) {
    case "apple":
        echo "Apple";
        break;
    default:
        echo "Unknown fruit";
}
?>

Grouping Switch Cases

Listing several case labels back-to-back with no code between them, followed by a single shared block, lets multiple distinct values trigger identical behavior without duplicating that block for each one.

Example: Grouping Switch Cases

php
<?php
$day = "Saturday";
switch ($day) {
    case "Saturday":
    case "Sunday":
        echo "Weekend";
        break;
    default:
        echo "Weekday";
}
?>

Alternative Colon Syntax

Like if, switch supports a colon-based alternative syntax closed with endswitch;, which keeps templates that mix PHP and HTML more readable than the brace-heavy default form would.

Example: Alternative Colon Syntax

php
<?php
$role = "admin";
switch ($role):
    case "admin":
        echo "Admin panel";
        break;
    default:
        echo "No access";
endswitch;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.