Use Match Expressions for Clean API Enum Mapping

๐Ÿ“– 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.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *