Benjamin Crozat “Heard about Sevalla? They let you deploy PHP apps with ease.” Claim $50 →

1 minute read

A quick look at the PHP match expression

If you still reach for switch, this post by Ashley Allen is a nice refresher on why match can be cleaner.

Key bits I liked:

  • match uses strict comparison (===), so types must match.
  • You can stack multiple cases in one arm.
  • match(true) lets you write simple rule checks.
  • It pairs well with enums and can be exhaustive without a default.

A tiny taste:

return match ($driver) {
    'github', 'self-hosted' => new GitHubDriver(),
    'gitlab'                 => new GitLabDriver(),
    'bitbucket'              => new BitbucketDriver(),
    default                  => throw new InvalidArgumentException(),
};

I found the enum example especially useful for turning stored values into friendly labels. If you are on PHP 8.0 or higher, this is an easy win for tidy code.

Read more on ashallendesign.co.uk →


Did you like this article? Then, keep learning:

Help me reach more people by sharing this article on social media!

0 comments

Guest

Markdown is supported.

Hey, you need to sign in with your GitHub account to comment. Get started →

Great deals for developers

Search for posts and links

Try to type something…