If you have been programming with PHP for some time, you have likely used the switch statement more times than you can remember. It does the trick, but it also brings a lot of baggage with it. The PHP match expression was introduced in PHP 8.0 as a better way to do what the switch statement does, making your code more readable and less prone to errors. In this tutorial, we will go over everything you need to know about it.
What is a Match Expression in PHP?
The match expression is a control structure introduced in PHP 8.0. It works similarly to switch, but with some important improvements. It compares a value against multiple conditions and returns a result based on the first match it finds.
Here is what makes it stand out:
- It uses strict comparison (===) instead of loose comparison (==)
- It returns a value, so you can assign it directly to a variable
- It throws an UnhandledMatchError if no condition matches and no default is set
- Each arm uses => instead of case and break
- It is shorter and cleaner to write
Why Should You Use Match Over Switch Statement?
It’s probably the most common question that developers ask when they first hear about the PHP match vs switch statement debate. The switch statement performs loose comparison which can easily lead to unexpected bugs that are hard to track down.
The match statement fixes this by always performing strict comparison. In addition to this, switch requires you to write break after every case, or else your code will fall through to the next case. In match, there is no fall-through. Every case is self-contained, which makes your code much safer and predictable.
In short, match gives you more control with less code.
PHP Match Expression Examples
Let us go through some practical examples. These cover the most common use cases you will encounter in real projects.
Basic Usage
Imagine you are building an e-commerce platform and want to show a message based on an order status. Let’s take an example of implementing same logic for showing message to user based on status using switch case and match expression:
Switch Case
$status = 'pending';
switch ($status) {
case 'pending':
$message = 'Your order is being processed.';
break;
case 'shipped':
$message = 'Your order is on the way!';
break;
case 'delivered':
$message = 'Your order has arrived.';
break;
default:
$message = 'Unknown status.';
break;
}
Match Expression
echo $message;
$status = 'pending';
$message = match ($status) {
'pending' => 'Your order is being processed.',
'shipped' => 'Your order is on the way!',
'delivered' => 'Your order has arrived.',
default => 'Unknown status.',
};
echo $message;
As you can see into both examples, the match expression looks more readable and cleaner then switch statement.
Multiple Conditions in a Single Arm
Sometimes, you need to check multiple values and for same result. Say you are building a file upload system and need to categorise files by their extension.
$extension = 'jpg';
$fileType = match ($extension) {
'jpg', 'jpeg', 'png', 'gif' => 'image',
'mp4', 'mov', 'avi' => 'video',
'mp3', 'wav' => 'audio',
default => 'unknown',
};
You can group multiple values in a single arm by separating them with commas. No need to repeat yourself. This keeps things tidy and avoids duplicate logic.
Conditional Matching with match
The match expression is not limited to exact value comparisons. You can use match(true) to evaluate conditions, much like an if-elseif chain. Consider a scenario where you want to categorise users by age on your platform:
$age = 25;
$category = match (true) {
$age < 13 => 'Child',
$age >= 13 && $age < 20 => 'Teenager',
$age >= 20 && $age < 65 => 'Adult',
default => 'Senior',
};
Each arm now holds a condition rather than a value. PHP evaluates them one by one and returns the result of the first one that is true. This pattern is especially useful when dealing with ranges or complex logic.
Instantiating Classes Based on a Value
Here is a real-world example from OAuth or social login integrations. You want to load the right driver based on a user’s choice.
$driverName = 'github';
$driver = match ($driverName) {
'github' => new GitHubDriver(),
'gitlab' => new GitLabDriver(),
'bitbucket' => new BitbucketDriver(),
default => throw new InvalidArgumentException("Driver [$driverName] not supported."),
};
Notice the throw inside the default arm. Since PHP 8.0, you can throw exceptions directly inside a match expression. If someone passes an unsupported driver name, the application fails loudly and clearly rather than silently doing the wrong thing.
Working with Enums in PHP Match
PHP 8.1 introduced Enums, and they pair beautifully with match. Suppose you have a role-based access system in your application. Another common use is for showing different labels as per case like showing into below example:
<?php
enum UserRole
{
case Admin;
case Editor;
case Guest;
public function label(): string
{
return match ($this) {
UserRole::Admin => 'Full Access',
UserRole::Editor => 'Edit Access',
UserRole::Guest => 'Read Only',
};
}
}
$role = UserRole::Admin;
echo $role->label();
With introduction of enums, it’s common to show different label for each case rather then showing key or value for each item.
Functional Execution Inside Match
The match expression allows us to utilize however it fits our requirement. Let’s take another example where you can perform function execution inside match. Think of a content management system where an editor can save, publish, or delete a post:
$action = 'publish';
$result = match ($action) {
'save' => $this->saveDraft(),
'publish' => $this->publishPost(),
'delete' => $this->deletePermanently(),
default => false,
};
Depending on the value of $action, the corresponding method gets called and its return value is stored in $result. This pattern keeps your controller or service logic tight and readable.
Conclusion
The PHP match expression is definitely one of the most exciting features that PHP 8.0 has to offer. It is more strict, secure, and much more readable than the classic switch statement. Whether you are matching simple values, ranges, Enums, or class methods, match has it all covered in a much more elegant and less error-prone way. If you still find yourself using switch statements out of habit, it is high time you gave the match expression a serious try in your next project.
