Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.

What switch is for

switch compares one expression against many discrete values.

Example

<?php

declare(strict_types=1);

$cmd = 'greet';

switch ($cmd) {
    case 'greet':
        echo "Hello\n";
        break;
    case 'exit':
        echo "Bye\n";
        break;
    default:
        echo "Unknown\n";
}

break and fall-through

break prevents fall-through to the next case. Forgetting break is a classic bug—PHP does not “auto-stop” between cases.

Exercise

Set $cmd = 2. Use switch so you echo the word two (no extra lines).

From Zero to PHP — Control flow, functions, arrays, and the web