Table of Contents
๐ 1 minute read
Mapping between your internal enums and an external API’s codes? PHP 8’s match() expression was built for this.
The Old Way
// โ Verbose and error-prone
function mapStatus(string $apiCode): string {
if ($apiCode === 'ACT') return 'active';
if ($apiCode === 'INA') return 'inactive';
if ($apiCode === 'PND') return 'pending';
if ($apiCode === 'CAN') return 'cancelled';
throw new \InvalidArgumentException("Unknown code: $apiCode");
}
The Clean Way
// โ
Exhaustive, readable, safe
function mapStatus(string $apiCode): string {
return match($apiCode) {
'ACT' => 'active',
'INA' => 'inactive',
'PND' => 'pending',
'CAN' => 'cancelled',
default => throw new \InvalidArgumentException(
"Unknown status code: $apiCode"
),
};
}
Why match() Is Better
- Strict comparison โ no type juggling surprises
- Expression, not statement โ can assign directly to a variable
- Exhaustive default โ forces you to handle unknown values
- Readable โ the mapping is a clean lookup table
Takeaway
Use match() for any code-to-value mapping. It’s cleaner than if/else chains, safer than arrays (because of the default throw), and reads like a lookup table.

Leave a Reply