switch
Pageturn sells paperbacks, hardbacks, ebooks and audiobooks, and the delivery cost depends on the format. A long chain of elseif ($format === ...) works, but it repeats $format on every line. switch compares one value against a list of cases instead.
The rule
switch jumps to the matching case and falls through until
break.
<?php
$format = "hardback";
switch ($format) {
case "paperback":
case "hardback":
$delivery = 3.50;
break;
case "ebook":
case "audio":
$delivery = 0;
break;
default:
$delivery = null; // unknown format
}The mechanics:
switch ($value)evaluates the value once.- PHP looks for the first
casethat equals it and starts running there. - It keeps running downward through the following cases until it meets
break(or the end). This is called fall-through. defaultruns when no case matched. It is optional but usually wise.
Fall-through is useful on purpose: stacking case "paperback": and case "hardback": with nothing between them makes both share one block, as above.
It is dangerous by accident. Forget one break and the next case's code runs as well:
switch ("ebook") {
case "ebook": echo "e"; // no break!
case "audio": echo "a"; break;
}
// prints: eaOne more detail: switch compares with loose equality (==), so types can be converted. switch ("1") will match case 1:. When exact types matter, the match expression in the next lesson compares strictly.
The shortcut
To predict a switch, find the entry point, then run downward until the first break. Do not stop at the next case label; labels are only entry points, not walls.
The value
$format = "paperback";in a switch where the paperback case sets$delivery = 3.50;but has nobreak.
Drills
Answer fast — trust the rule.
In the delivery switch above, what is $delivery for "audio"?
What stops execution from continuing into the next case?
A switch on "poster" has cases for four book formats and a default. What runs?
Which comparison does switch use to match cases?
Remember
- switch jumps to the matching case and falls through until
break. - Shortcut: find the entry point, then run down to the first break.
- Trap: a forgotten break runs the next case too, and switch compares loosely.
