PHPackages                             bentools/cartesian-product - 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. bentools/cartesian-product

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

bentools/cartesian-product
==========================

A simple, low-memory footprint function to generate all combinations from a multi-dimensionnal array.

2.0.1(10mo ago)87905.6k↓12.6%1218MITPHPPHP ^8.2CI passing

Since May 30Pushed 10mo ago3 watchersCompare

[ Source](https://github.com/bpolaszek/cartesian-product)[ Packagist](https://packagist.org/packages/bentools/cartesian-product)[ RSS](/packages/bentools-cartesian-product/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (12)Used By (18)

[![Latest Stable Version](https://camo.githubusercontent.com/b652526b99bc5bfe66092d314144ea3030c9564aa6f18eb9dcf3d462ffcf5428/68747470733a2f2f706f7365722e707567782e6f72672f62656e746f6f6c732f63617274657369616e2d70726f647563742f762f737461626c65)](https://packagist.org/packages/bentools/cartesian-product)[![License](https://camo.githubusercontent.com/618502e1fe6440fdfeb36333f937d3c20548969ac44af9c5be5b7e0e125aa258/68747470733a2f2f706f7365722e707567782e6f72672f62656e746f6f6c732f63617274657369616e2d70726f647563742f6c6963656e7365)](https://packagist.org/packages/bentools/cartesian-product)[![CI Workflow](https://github.com/bpolaszek/cartesian-product/actions/workflows/ci-workflow.yml/badge.svg)](https://github.com/bpolaszek/cartesian-product/actions/workflows/ci-workflow.yml)[![Coverage](https://camo.githubusercontent.com/f0938e57cf82b1902b73e0d6d038c6b9fb13449aaaeb849f1eb23419f7c2f561/68747470733a2f2f636f6465636f762e696f2f67682f62706f6c61737a656b2f63617274657369616e2d70726f647563742f6272616e63682f6d61737465722f67726170682f62616467652e7376673f746f6b656e3d33434635514830434b47)](https://codecov.io/gh/bpolaszek/cartesian-product)[![Total Downloads](https://camo.githubusercontent.com/65e7d553ae64484595ecdcd952e0973e3e4272ebb95b950ca8ab38d678e25f60/68747470733a2f2f706f7365722e707567782e6f72672f62656e746f6f6c732f63617274657369616e2d70726f647563742f646f776e6c6f616473)](https://packagist.org/packages/bentools/cartesian-product)

Cartesian Product
=================

[](#cartesian-product)

A simple, low-memory footprint function to generate all combinations from a multi-dimensionnal array.

Usage
-----

[](#usage)

```
use function BenTools\CartesianProduct\combinations;

$data = [
    'hair' => [
        'blond',
        'black'
    ],
    'eyes' => [
        'blue',
        'green',
        function (array $combination) { // You can use closures to dynamically generate possibilities
            if ('black' === $combination['hair']) { // Then you have access to the current combination being built
                return 'brown';
            }
            return 'grey';
        }
    ]
];

foreach (combinations($data) as $combination) {
    printf('Hair: %s - Eyes: %s' . PHP_EOL, $combination['hair'], $combination['eyes']);
}
```

Output:

```
Hair: blond - Eyes: blue
Hair: blond - Eyes: green
Hair: blond - Eyes: grey
Hair: black - Eyes: blue
Hair: black - Eyes: green
Hair: black - Eyes: brown

```

Array output
------------

[](#array-output)

Instead of using `foreach` you can dump all possibilities into an array.

Warning

This will dump all combinations in memory, so be careful with large datasets.

```
print_r(combinations($data)->asArray());
```

Output:

```
Array
(
    [0] => Array
        (
            [hair] => blond
            [eyes] => blue
        )

    [1] => Array
        (
            [hair] => blond
            [eyes] => green
        )

    [2] => Array
        (
            [hair] => blond
            [eyes] => grey
        )

    [3] => Array
        (
            [hair] => black
            [eyes] => blue
        )

    [4] => Array
        (
            [hair] => black
            [eyes] => green
        )

    [5] => Array
        (
            [hair] => black
            [eyes] => brown
        )

)
```

Combinations count
------------------

[](#combinations-count)

You can simply count how many combinations your data produce (this will not generate any combination):

```
use function BenTools\CartesianProduct\combinations;

$data = [
    'hair' => [
        'blond',
        'red',
    ],
    'eyes' => [
        'blue',
        'green',
        'brown',
    ],
    'gender' => [
        'male',
        'female',
    ]
];
var_dump(count(combinations($data))); // 2 * 3 * 2 = 12
```

Filtering combinations
----------------------

[](#filtering-combinations)

You can filter combinations using the `filter` method. This is useful if you want to skip some combinations based on certain criteria:

```
use function BenTools\CartesianProduct\combinations;

$data = [
    'hair' => [
        'blond',
        'black'
    ],
    'eyes' => [
        'blue',
        'green',
    ]
];

foreach (combinations($data)->filter(fn (array $combination) => 'green' !== $combination['eyes']) as $combination) {
    printf('Hair: %s - Eyes: %s' . PHP_EOL, $combination['hair'], $combination['eyes']);
}
```

Map output
----------

[](#map-output)

You can use the `each` method to transform each combination into a different format:

```
use App\Entity\Book;

use function BenTools\CartesianProduct\combinations;

$books = [
    'author' => ['Isaac Asimov', 'Arthur C. Clarke'],
    'genre' => ['Science Fiction', 'Fantasy'],
]

foreach (combinations($books)->each(fn (array $combination) => Book::fromArray($combination)) as $book) {
    assert($book instanceof Book);
}
```

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

[](#installation)

PHP 8.2+ is required.

```
composer require bentools/cartesian-product

```

Performance test
----------------

[](#performance-test)

The following example was executed on my Core i7 personnal computer with 8GB RAM.

```
use function BenTools\CartesianProduct\combinations;

$data = array_fill(0, 10, array_fill(0, 5, 'foo'));

$start = microtime(true);
foreach (combinations($data) as $c => $combination) {
    continue;
}
$end = microtime(true);

printf(
    'Generated %d combinations in %ss - Memory usage: %sMB / Peak usage: %sMB',
    ++$c,
    round($end - $start, 3),
    round(memory_get_usage() / 1024 / 1024),
    round(memory_get_peak_usage() / 1024 / 1024)
);
```

Output:

> Generated 9765625 combinations in 1.61s - Memory usage: 0MB / Peak usage: 1MB

Unit tests
----------

[](#unit-tests)

```
./vendor/bin/pest

```

Other implementations
---------------------

[](#other-implementations)

[th3n3rd/cartesian-product](https://github.com/th3n3rd/cartesian-product)

[patchranger/cartesian-iterator](https://github.com/PatchRanger/cartesian-iterator)

[Benchmark](https://github.com/PatchRanger/php-cartesian-benchmark)

See also
--------

[](#see-also)

[bentools/string-combinations](https://github.com/bpolaszek/string-combinations)

[bentools/iterable-functions](https://github.com/bpolaszek/php-iterable-functions)

Credits
-------

[](#credits)

[Titus](https://stackoverflow.com/a/39174062) on StackOverflow - you really rock.

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance54

Moderate activity, may be stable

Popularity52

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 89.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 ~296 days

Recently: every ~321 days

Total

11

Last Release

313d ago

Major Versions

1.5 → 2.02025-07-09

PHP version history (3 changes)1.0PHP &gt;=5.6

1.4PHP &gt;=7.4

2.0PHP ^8.2

### Community

Maintainers

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

---

Top Contributors

[![bpolaszek](https://avatars.githubusercontent.com/u/5569077?v=4)](https://github.com/bpolaszek "bpolaszek (26 commits)")[![hannesvdvreken](https://avatars.githubusercontent.com/u/1410358?v=4)](https://github.com/hannesvdvreken "hannesvdvreken (1 commits)")[![ostrolucky](https://avatars.githubusercontent.com/u/496233?v=4)](https://github.com/ostrolucky "ostrolucky (1 commits)")[![progdog-ru](https://avatars.githubusercontent.com/u/68942249?v=4)](https://github.com/progdog-ru "progdog-ru (1 commits)")

---

Tags

arraycartesiancombinationsfunctionphpproduct

###  Code Quality

TestsPest

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/bentools-cartesian-product/health.svg)

```
[![Health](https://phpackages.com/badges/bentools-cartesian-product/health.svg)](https://phpackages.com/packages/bentools-cartesian-product)
```

###  Alternatives

[facile-it/php-codec

A partial porting of io-ts in PHP

106.7k](/packages/facile-it-php-codec)

PHPackages © 2026

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