Beginner Fundamentals

PHP Switch

The switch statement compares one value against many possible options. It is a clean alternative to long if/elseif chains.

Basic switch

<?php
$day = "Mon";

switch ($day) {
    case "Mon":
        echo "Start of the week";
        break;
    case "Fri":
        echo "Almost weekend";
        break;
    default:
        echo "Just another day";
}

The break keyword

break stops the switch once a match is found. Without it, execution continues into the next case, which is usually not what you want.

<?php
$x = 1;
switch ($x) {
    case 1:
        echo "One";
        // no break: falls through
    case 2:
        echo "Two";
        break;
}
// Output: OneTwo

The default case

default runs when no case matches. It is optional but recommended.

Grouping cases

Several cases can share the same code.

<?php
$letter = "a";
switch ($letter) {
    case "a":
    case "e":
    case "i":
        echo "Vowel";
        break;
    default:
        echo "Consonant";
}