Lesson 43 of 100
Control flow15 min5 checksPHP 8.5

Choose Branches with switch

Learn how switch compares one value against many cases, how grouped cases and fallthrough work, and how to avoid missing-break bugs.

01 · THE IDEAREAD → TRY → LEARN

When switch fits

A switch statement evaluates one expression once and compares the result with each case value in order. It is a good fit when you ask the same question of one value many times: "which status is this?" or "which day code is this?". A long chain of if and elseif tests would work, but switch states the intent more clearly.

Example
<?php
$status = 'paid';
switch ($status) {
    case 'new':
        echo "Waiting\n";
        break;
    case 'paid':
        echo "Ready to ship\n";
        break;
    default:
        echo "Unknown status\n";
}
Output
Ready to ship

PHP finds the first matching case, then starts running statements. The default branch handles every value that no case matched. By convention it goes last, although PHP allows it elsewhere. A switch may have only one default. With no match and no default, nothing runs.

Execution continues until break

The most important detail is that a match only decides where execution starts. PHP keeps running statements through the following cases until it reaches break or the end of the block. This is called fallthrough.

Example
<?php
function describe(int $n): string
{
    $parts = [];
    switch ($n) {
        case 0:
            $parts[] = 'zero';
        case 1:
            $parts[] = 'one';
        case 2:
            $parts[] = 'two';
    }
    return implode(',', $parts);
}
echo json_encode([describe(0), describe(1), describe(2), describe(3)]) . "\n";
Output
["zero,one,two","one,two","two",""]

Passing 0 runs all three assignments, 1 runs two, 2 runs one, and 3 matches nothing. Forgetting break is the classic switch bug. When you return from inside a case, as in the exercise below, the function ends right away, so no break is needed after that return.

Grouping cases on purpose

An empty case body passes control to the next case. This is the clean way to say "these values share one result":

  • case 'sat': followed directly by case 'sun': and one shared body
  • several codes that all mean the same thing

Use grouping only when the case bodies are truly empty. If a non-empty body falls through to another case, add a comment so readers know it is intentional.

Loose comparison

The manual notes that switch uses loose comparison, like ==. That means types can be converted before values are compared.

Example
<?php
$value = '1';
switch ($value) {
    case 1:
        echo "matched integer 1\n";
        break;
    default:
        echo "no match\n";
}
Output
matched integer 1

The string '1' matches the integer case. If exact types matter, normalize the input first, for example by validating or casting it. Alternatively, use if with ===, or consider match, which compares strictly.

Conditions with switch (true)

A case expression is evaluated by itself and then compared to the switch value. It cannot inspect the switch value in a more complex way. For ranges, switch on true and make each case a boolean expression:

Example
<?php
function band(int $score): string
{
    switch (true) {
        case $score >= 90:
            return 'A';
        case $score >= 80:
            return 'B';
        default:
            return 'C';
    }
}
$out = [];
foreach ([95, 85, 20] as $s) {
    $out[] = band($s);
}
echo json_encode($out) . "\n";
Output
["A","B","C"]

Order matters here: the first true case wins, so put the strictest condition first. Because loose comparison with true accepts any truthy value, keep each case expression a real boolean.

Other details

  • Inside a loop, continue acts like break for a switch. Use continue 2 to move to the next iteration of the enclosing loop.
  • Write case value: with a colon. A semicolon after a case is allowed in PHP 8.4, but the manual says it is deprecated from PHP 8.5.0.
  • The alternative switch (...): ... endswitch; form exists but the braces form is more common.

Worked plan for the exercise

You will write classifyDay(string $day): string. The three-letter lowercase codes mon to fri should return weekday, sat and sun should return weekend, and anything else should return unknown. Group the five weekday cases together, group the two weekend cases, and finish with default. Returning directly from each group avoids fallthrough entirely.

Recap

switch evaluates once, jumps to the first loosely equal case, and runs on until break, return, or the end. Group values with empty cases, always provide a sensible default, and watch for accidental fallthrough.

Before you start

Functions · Arrays · Types

You’ll practice
  • Handle grouped cases and prevent fallthrough mistakes
  • Implement and test a deterministic PHP 8.4 function
Your task

Make classifyDay() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.