Maybe you hadn’t heard about the existence of the match() expression in PHP. It’s something that was added in version 8.
At first glance, it looks like a switch:
$value = 2;
$valueInLetters = match($value) { 1 => 'One', 2 => 'Two' };
echo $valueInLetters;
But it has some differences:
match() returns a value
The match expression returns a value that we can store in a variable or not. In the example, we store it in the variable $valueInLetters.
If a match is not found, match() fails
This code would trigger an error:
$value = 3;
$valueInLetters = match($value) { 1 => 'One', 2 => 'Two' };
echo $valueInLetters;
because match() is not happy if it can’t find the value we passed to it.
In the official documentation, they refer to this as: “A match expression must be exhaustive.”
Once a match is found, it doesn’t continue
If the value is 1, it doesn’t try 2 and directly returns the corresponding value. We don’t need to include a break.
Values are compared using ===
This example would fail because 1 is not exactly equal to 1.0:
$value = 1.0;
$valueInLetters = match($value) { 1 => 'One', 2 => 'Two' };
echo $valueInLetters;
We can use default
Just like with switch, we can use default for cases we haven’t accounted for:
$value = 1.0;
$valueInLetters = match($value) { 1 => 'One', 2 => 'Two', default => 'I don't know what number it is' };
echo $valueInLetters;
We can use multiple values in each case
And we can also use multiple values for each of the options:
$value = 1.0;
$valueInLetters = match($value) { 1, 1.0 => 'One', 2, 2.0 => 'Two', default => 'I don't know what number it is' };
echo $valueInLetters;