Most languages have a switch
statement or a similar construct. The PHP switch
handles multiple cases: we have a variable, and test for many possible values.
With switch
, we impart some symmetry to our programs. Usually we use "if" first, but in rewriting a program, changing to a switch
may help it be more maintainable.
This program shows 3 versions of code that assigns a string
to a literal value based on an integer. We test the bird_count
integer.
switch
statement on the bird_count
, which is equal to 1. The second case (case 1) matches, and our string
equals "One bird."if
-elseif
to handle all the cases. This version can be changed to support "greater" and "less than" tests.$bird_count = 1; // Version 1: use switch to get bird count message. $result = ""; switch ($bird_count) { case 0: $result = "No birds"; break; case 1: $result = "One bird"; break; case 2: $result = "Two birds"; break; default: $result = "Many birds"; } var_dump($result); // Version 2: use match to get message string. $result = match ($bird_count) { 0 => "No birds", 1 => "One bird", 2 => "Two birds", default => "Many birds", }; var_dump($result); // Version 3: use if/elseif/else to get message string. $result = ""; if ($bird_count == 0) { $result = "No birds"; } elseif ($bird_count == 1) { $result = "One bird"; } elseif ($bird_count == 2) { $result = "Two birds"; } else { $result = "Many birds"; } var_dump($result);string(8) "One bird" string(8) "One bird" string(8) "One bird"
In newer versions of PHP (like 8 onwards) we can use match instead of switch
for clearer, simpler syntax. But switch
still has some utility as it can support multiple statements in a case.