Pattern Matching in PHP
Learn about pattern matching functionality in a functional-php library.
We'll cover the following
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 elaborate sequences (patterns). Enter pattern matching. This is a solution that allows for value recognition and variable binding. Any combination of objects, variables, and even constants constitutes a pattern. The domain is quite large.
Patterns are either primitive (exclusive to a single value) or tree-like and complex (composable from multiple primitives). A URL, for instance, is a tree pattern. It not only contains a structure, but it also features a host, a port, a path, and, occasionally, either a username or even a password.
The syntax of patterns is not limited to primitives, it extends to include wildcards and cons. A wildcard (_
) is a generic pattern that symbolizes values of no concern. Cons—trees composed of primitives separated by a prepend operator (:
)—are lists derived from the recursive applications on an empty list.
The workaround for pattern matching in PHP is the hash table (array) syntax. This syntax is convenient for key-value bindings. The patterns take on a string index form and the corresponding lambdas assume the value form. The pattern-matching library, functional-php/pattern-matching
, offers such a solution, as well as a tabular catalog of compatible patterns.
An example of pattern matching
To demonstrate the effectiveness of pattern matching, let’s look at the example of a simple router for resolving and matching routes, ideally entered through address bar, to concrete endpoints. Some endpoints, or URL path fragments, are defined in the table below to mimic the resources available on a simple blog platform.
Path | Purpose |
---|---|
/posts |
Get the list of available blog posts. |
/posts/{id} |
Fetch details about a single blog post. |
Note: The endpoints dependent on the use of
POST
andPUT
methods are absent here as the implementation of said methods is beyond the scope of the example context.
The following snippet features multiple compositions in a router
function whose return value is a string—a JSON encoded block of array data.
Get hands-on with 1400+ tech skills courses.