Home
PHP
switch Example (case, break)
This page was last reviewed on May 21, 2023.
Dot Net Perls
Switch. 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.
Version 1 We use a switch statement on the bird_count, which is equal to 1. The second case (case 1) matches, and our string equals "One bird."
Version 2 We use match, a newer feature found in PHP 8. We handle the same cases but with "fat" arrow syntax.
Version 3 We use if-elseif to handle all the cases. This version can be changed to support "greater" and "less than" tests.
if
$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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 21, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.