300 words, 2 min read

Pattern matching is a powerful technique that makes your code more declarative and expressive. In TypeScript, libraries like ts-pattern let you write concise and readable logic such as:

const companySlug = match(useCompanyStore().company?.slug)
.with(P.string.startsWith('acme-'), () => 'acme')
.with(P.string.startsWith('test-acme'), () => 'acme')
.otherwise((value) => value);

Unfortunately, PHP doesn’t have a built-in equivalent for this kind of predicate-based pattern matching. However, we can express the same logic in a few elegant ways.

Using match (true)

PHP 8 introduced the match expression, which is similar to a switch, but with better semantics. Although it only supports strict comparisons, you can use match (true) to make it behave like predicate matching:

$slug = $companyStore->company->slug ?? null;
$companySlug = match (true) {
$slug === null => null,
str_starts_with($slug, 'acme-') => 'acme',
str_starts_with($slug, 'test-acme') => 'acme',
default => $slug,
};

This pattern uses boolean conditions inside match branches. Each expression is evaluated top to bottom, and the first matching condition wins.

It’s compact, expressive, and easy to maintain β€” a good native alternative to the TypeScript example.

Classic conditional approach

If you prefer a more explicit, imperative style, a simple conditional chain works just as well:

$slug = $companyStore->company->slug ?? null;
if ($slug === null) {
$companySlug = null;
} elseif (str_starts_with($slug, 'acme-')) {
$companySlug = 'acme';
} elseif (str_starts_with($slug, 'test-acme')) {
$companySlug = 'acme';
} else {
$companySlug = $slug;
}

This version is straightforward and familiar to most PHP developers. It’s slightly more verbose, but arguably the most readable when conditions get complex.

When to use which

  • Use match (true) when you want compact, declarative mappings.
  • Use if/elseif chains when readability or debugging matters most.
  • If you have many pattern rules, consider extracting them into a reusable helper or lookup table.

Both approaches are valid β€” what matters is clarity and maintainability for your team.