🐥 Pattern matching alternatives in PHP
yellowduck.be·22h
Flag this post

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, …

Similar Posts

Loading similar posts...