switch: many cases, one choice
When one variable can have many values and each needs different code, a chain of if and elseif gets long. A switch is neater: switch ($x) compares $x with each case in turn and starts running at the first match. It keeps running until it meets a break; so break means “leave the switch”. If you forget the break, the code of the next case runs as well: this is called falling through. Sometimes it is useful: stacked cases such as case 1: case 2: case 3: share one block, exactly like if ($a == 1 || $a == 2 || $a == 3). The default case runs when nothing matches. Be careful with one word: break leaves only the switch, but exit ends the whole script, so nothing after it is run. The book says that exit leaves the switch; that is not right in PHP. Always write the variable in the first line as $x = 1; with an equals sign.
1<?php 2$day = 3; 3switch ($day) { 4 case 1: 5 echo "Chess"; 6 break; 7 case 2: 8 echo "Drawing"; 9 break; 10 case 3: 11 echo "Football"; 12 break; 13 default: 14 echo "No club"; 15} 16?>
Football
1<?php 2$a = 2; 3switch ($a) { 4 case 1: 5 case 2: 6 case 3: 7 echo "1 or 2 or 3"; 8 break; 9 default: 10 echo "other"; 11} 12?>
1 or 2 or 3
1<?php 2switch (1) { 3 case 1: 4 echo "one "; 5 case 2: 6 echo "two"; 7 break; 8 case 3: 9 echo "three"; 10} 11?>
one two
| Code | Output |
|---|---|
| case 1: echo "A"; break; … echo "B"; | AB |
| case 1: echo "A"; exit; … echo "B"; | A |
Write on paper a switch for the numbers 1 to 4 that prints the name of a season of your choice, with a default that prints “not a season”. Then change it so that 1 and 2 share the same word, and test it with 1, 2, 4 and 9.