Table of Contents

5. 'Match' — Declarative Branching With Shape and Intent

Modern PHP gives us a more expressive way to handle branching logic.
match is not a prettier switch.
It’s a declarative expression that returns a value, enforces completeness, and makes intent explicit.

It reflects how PHP 8+ wants us to think:

AI gets match wrong often.
It mixes it with switch, forgets exhaustiveness,
or uses it where a simple if would be clearer.


1. What 'match' Is

match is an expression that:

It’s branching with guardrails.


2. Why Modern PHP Uses 'match'

match gives us:

match is ideal when branching is structural,
not behavioral.


3. The Mental Model

match is data‑shaped branching.

It’s not about control flow.
match is about mapping one-value-to-another
in a way that is:

The key idea:


4. A Simple Example

$status = match ($code) {
    200 => 'OK',
    404 => 'Not Found',
    500 => 'Server Error',
};

This is not a control structure.
It’s a value expression.


5. When to Use 'match'

Use match when:

It shines in DTOs, controllers, transformers, and small decision boundaries.


6. When Not to Use match

Avoid match when:

match is for selection,
not execution
.

When AI Gets This Wrong

AI often treats match like a modern switch, using it for side effects or procedural logic.
Sometimes it forgets to handle all cases, mixes types, or nests match expressions unnecessarily.
Our mental model helps us see when match is the right tool
— and when AI is using it simply because it “looks modern”.


Summary

match gives us a declarative, predictable way to map values.
It enforces completeness, avoids fall‑through, and keeps branching aligned with the shape of the data.

Once we internalize this,
we can immediately see when AI‑generated code:

  1. uses match for work instead of selection
  2. forgets to handle all cases
  3. mixes types in a way that breaks exhaustiveness
  4. or misses opportunities to use match where it clarifies intent

match is a small feature
— but it teaches us how modern PHP wants to express decisions.

A tiny aside:
To match or not to match…
every match expression begins with a question.
The important part is choosing the right stage for the answer.