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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help