PHPackages                             functional-php/pattern-matching - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. functional-php/pattern-matching

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

functional-php/pattern-matching
===============================

Pattern matching for PHP with automatic destructuring.

1.0.0(4y ago)8268.2k—8.7%4[7 issues](https://github.com/functional-php/pattern-matching/issues)BSD-3-ClausePHPPHP &gt;=5.6.0

Since Oct 24Pushed 4y ago3 watchersCompare

[ Source](https://github.com/functional-php/pattern-matching)[ Packagist](https://packagist.org/packages/functional-php/pattern-matching)[ RSS](/packages/functional-php-pattern-matching/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (1)Dependencies (3)Versions (6)Used By (0)

Pattern Matching
================

[](#pattern-matching)

[![pattern-matching CI](https://github.com/ace411/pattern-matching/actions/workflows/php.yml/badge.svg?branch=master)](https://github.com/ace411/pattern-matching/actions/workflows/php.yml)[![StyleCI](https://camo.githubusercontent.com/bdf5689308ece7eaf2ef064bd49076b9e506e061c2989344057fa84049071295/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3334313434303531382f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/341440518?branch=master)[![Code Coverage](https://camo.githubusercontent.com/1cefa10a062ffd42926f64b9f1837688d86e770e4c2a74fa639ba20c9a6deee5/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f66756e6374696f6e616c2d7068702f7061747465726e2d6d61746368696e672f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/functional-php/pattern-matching/?branch=master)[![Average time to resolve an issue](https://camo.githubusercontent.com/dfddb0a1f817a3d8280e0e4cb66bbea9ab34c131df1ee114d231bc32433149ec/687474703a2f2f697369746d61696e7461696e65642e636f6d2f62616467652f7265736f6c7574696f6e2f66756e6374696f6e616c2d7068702f7061747465726e2d6d61746368696e672e737667)](http://isitmaintained.com/project/functional-php/pattern-matching "Average time to resolve an issue")[![Percentage of issues still open](https://camo.githubusercontent.com/c40c02917385daf3199187611748eb7cbfc273343dc4c8a77a572ad7abed0330/687474703a2f2f697369746d61696e7461696e65642e636f6d2f62616467652f6f70656e2f66756e6374696f6e616c2d7068702f7061747465726e2d6d61746368696e672e737667)](http://isitmaintained.com/project/functional-php/pattern-matching "Percentage of issues still open")[![Chat on Gitter](https://camo.githubusercontent.com/ef03cfbbd5ec62aaabc567543aab69fdf2c97d9efb7b8374d9aa2cef00a6d912/68747470733a2f2f696d672e736869656c64732e696f2f6769747465722f726f6f6d2f67697474657248512f6769747465722e737667)](https://gitter.im/functional-php)

Pattern matching is the process of checking a series of token against a pattern. It is different from pattern recognition as the match needs to be exact. The process does not only match as a switch statement does, it also assigns the value a bit like the `list` construct in PHP, a process called **destructuring**.

Most functional languages implement it as a core feature. Here is are some small examples in Haskell:

```
fact :: (Integral a) => a -> a
fact 0 = 1
fact n = n * fact (n-1)

head :: [a] -> a
head xs = case xs of []    -> error "empty list"
                     (x:_) -> x

firstThree :: [a] -> (a, a, a)
firstThree (x:y:z:_) = (x, y, z)
firstThree _ = error "need at least 3 elements"
```

If you want to read more about the topic, you can head over to Wikipedia : [Pattern matching](https://en.wikipedia.org/wiki/Pattern_matching)

Installation
------------

[](#installation)

```
composer require functional-php/pattern-matching

```

Basic Usage
-----------

[](#basic-usage)

As we cannot extend the syntax of PHP, the choice was made to use a syntax based on arrays. The key representes the pattern and the value is the function to call with the value or a constant if you want to do nothing with it.

Let's see how we could implement our 3 Haskell examples:

```
use FunctionalPHP\PatternMatching as m;

$fact = m\func([
    '0' => 1,
    'n' => function($n) use(&$fact) {
        return $n * $fact($n - 1);
    }
]);

$head = m\func([
    '(x:_)' => function($x) { return $x; },
    '_' => function() { throw new RuntimeException('empty list'); }
]);

$firstThree= m\func([
    '(x:y:z:_)' => function($x, $y, $z) { return [$x, $y, $z]; },
    '_' => function() { throw new RuntimeException('need at least 3 elements'); }
]);
```

You can also use the `match` function if you want to have a beefed up version of the `switch` statement or if you don't like anonymous functions:

```
use FunctionalPHP\PatternMatching as m;

function factorial($n) {
    return m\pmatch([
        '0' => 1,
        'n' => function($n) use(&$fact) {
            return $n * factorial($n - 1);
        }
    ], $n);
}

echo m\pmatch([
    '"toto"' => 'first',
    '[a, [b, c], d]' => 'second',
    '[a, _, (x:xs), c]' => 'third',
    '_' => 'default',
], [1, 2, ['a', 'b'], true]);
// third
```

If you are just interested in destructuring your values, there is also a helper for that:

```
use FunctionalPHP\PatternMatching as m;

print_r(m\extract([1, 2, ['a', 'b'], true], '[a, _, (x:xs), c]'));
// Array (
//     [a] => 1
//     [x] => a
//     [xs] => Array ( [0] => b )
//     [c] => 1
// )
```

Patterns
--------

[](#patterns)

Here is a quick recap of the available patterns:

NameFormatExampleConstantAny scalar value (int, float, string, boolean)`1.0`, `42`, "test"Variable`identifier``a`, `name`, `anything`Array`[, ..., ]``[]`, `[a]`, `[a, b, c]`Cons`(identifier:list-identifier)``(x:xs)`, `(x:y:z:xs)`Wildcard`_``_`As`identifier@()``all@(x:xs)`Testing
-------

[](#testing)

You can run the test suite for the library using:

```
composer test

```

A test report will be available in the `reports` directory.

Contributing
------------

[](#contributing)

Any contribution welcome :

- Ideas
- Pull requests
- Issues

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community15

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 61.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~430 days

Total

5

Last Release

1795d ago

Major Versions

0.3.1 → 1.0.02021-07-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/511338e7e9e4e1e5a7c99656dc2c746fe72c5680486c38504d244437c34555c0?d=identicon)[widmogrod](/maintainers/widmogrod)

![](https://www.gravatar.com/avatar/fb9a0c8a1351bb031632b9f7803cd89cfb25068a29a47aa3775f160a3bc966ae?d=identicon)[ace411](/maintainers/ace411)

![](https://avatars.githubusercontent.com/u/422139?v=4)[Lukáš Marek](/maintainers/krtek)[@krtek](https://github.com/krtek)

---

Top Contributors

[![krtek4](https://avatars.githubusercontent.com/u/963772?v=4)](https://github.com/krtek4 "krtek4 (37 commits)")[![ace411](https://avatars.githubusercontent.com/u/11040337?v=4)](https://github.com/ace411 "ace411 (23 commits)")

---

Tags

functionalpatternPattern Matchingdestructuring

###  Code Quality

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/functional-php-pattern-matching/health.svg)

```
[![Health](https://phpackages.com/badges/functional-php-pattern-matching/health.svg)](https://phpackages.com/packages/functional-php-pattern-matching)
```

###  Alternatives

[lstrojny/functional-php

Functional primitives for PHP

2.0k7.5M50](/packages/lstrojny-functional-php)[league/pipeline

A plug and play pipeline implementation.

1.0k16.8M84](/packages/league-pipeline)[nikic/iter

Iteration primitives using generators

1.1k6.2M51](/packages/nikic-iter)[lambdish/phunctional

λ PHP functional library

3632.1M24](/packages/lambdish-phunctional)[qaribou/immutable.php

Immutable, highly-performant collections, well-suited for functional programming and memory-intensive applications.

347147.4k](/packages/qaribou-immutablephp)[crell/fp

Functional utilities for PHP 8 and later

92490.8k11](/packages/crell-fp)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
