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.
$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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.