Use a match statement for advanced PHP data checks
A new feature introduced in PHP 8 is a match
statement, which is an alternative to the switch
statement.
Some complaints about switch
statements have been that it’s a bit too verbose, you can forget to include a break
keyword and your logic will get messed up, and that the conditional check is loose rather than strict. The match
statement aims to solve all of these issues.
Let’s rewrite this switch
statement to use a match
statement instead.
The first major change is that we will assign the match
statement to a variable. So let’s create our $message
variable and assign it to a match statement.
This implies right away that a value is returned from a match.
Next comes the values we wish to match. We’ll type 0
for matching 0 posts, and then assign it the value of “There are no posts.”. Note how we assign values here — it’s an equal sign followed by a greater than sign. This is how key:value assignments are made in PHP. The key is the 0, and the value is “There are no posts.”.
$message = match ($numPosts) { 0 => 'There are no posts.', };
Since this is a variable assignment, we also need to make sure to end the match statement with a semicolon.
With key:value assignments, it’s common to add more assignments in later, so it’s a good idea to end every one of your lines with a comma. If you use version control, making updates to these key value assignments will lead to cleaner diffs of your code.
Let’s create another possible match, for 1. But let’s add on a 2 and 3 as well. This is a huge spot where match
differs from switch
. Rather than typing case
every time, we can just right out the numbers delimited by commas. Let’s return “There are some posts.”.
You may have noticed something else as well: there are no break
statements with match
. As soon as a condition is matched, it returns that value and exits out of the match statement. This can lead to code that is a bit easier to understand, and you never need to worry about forgetting it.
And finally, just like switch
we can define a default
. For this value, we can return “There are many posts”.
And just like that, we have the same logic as our switch case
. In addition, note that this is a strict data check, which means that if we pass in a string, it will not catch any resulting matches with a different data type. (change 10 to ‘3’ to test).
<?php $title = 'My Blog'; $numPosts = 10; $hasPosts = $numPosts > 0; $numPostsDisplay = "\\"$numPosts\\" posts"; $message =match($numPosts) { 0 => 'There are no posts.', 1, 2, 3 => 'There are a few posts.', default => 'There are many posts.', }; ?> <h1><?=$title?></h1> <h2><?=$numPostsDisplay?></h2> <p><?=$message?></p>