Search⌘ K

Pattern Matching in PHP

Explore how to apply pattern matching in PHP to match values and extract data structures. Learn the difference between switch statements and pattern matching, understand primitives, wildcards, cons patterns, and see practical use cases such as routing for web applications.

Not to be confused with regular expression matching, pattern matching is a means of matching patterns against values. It’s rather straightforward. Pattern matching is immanent in the designs of languages like Haskell and Elm and is not organically supported in PHP. Among the mitigations of the innately absent pattern matching is the package aptly named functional-php/pattern-matching, created and maintained by Gilles Crettenand. It allows the usage of pattern matching syntax similar to Haskell and also enables pattern value extraction.

Switch vs. pattern matching

The switch statement is a pervasive control structure and is often used to differentiate discernible selections. It’s used for flow control but is not expressive enough to accommodate ...