PHPackages                             baraja-core/combinations - 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. baraja-core/combinations

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

baraja-core/combinations
========================

Smart algorithms about combinations and generators.

v2.0.0(5y ago)145.8k1PHPPHP ^8.0CI passing

Since Nov 1Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/combinations)[ Packagist](https://packagist.org/packages/baraja-core/combinations)[ Docs](https://github.com/baraja-core/combinations)[ RSS](/packages/baraja-core-combinations/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (4)Versions (9)Used By (1)

Combinations
============

[](#combinations)

Smart algorithms for generating all possible combinations (Cartesian product) from multiple sets of values.

This PHP library provides a simple, efficient way to generate every possible combination from an associative array where each key contains an array of possible values. Perfect for generating product variants, configuration matrices, test scenarios, and any situation requiring exhaustive combination enumeration.

✨ Key Principles
----------------

[](#-key-principles)

- **Cartesian Product Generation** - Computes all possible combinations from multiple value sets
- **Key Preservation** - Original associative keys are preserved in the output combinations
- **Value Uniqueness Enforcement** - All values across all keys must be unique to ensure unambiguous key mapping
- **Strict Input Validation** - Validates input format before processing to prevent runtime errors
- **Combination Counting** - Ability to count total combinations without generating them (memory efficient)
- **Type Safety** - Strict PHP 8.0+ typing with PHPStan level 8 analysis

🏗️ Architecture
---------------

[](#️-architecture)

The library consists of a single, focused class that handles all combination generation logic:

```
┌─────────────────────────────────────────────────────────────┐
│                   CombinationGenerator                      │
├─────────────────────────────────────────────────────────────┤
│  Public Methods:                                            │
│  ├── generate(array $input): array                          │
│  │   └── Returns all combinations with preserved keys       │
│  └── countCombinations(array $input): int                   │
│      └── Returns total count without generating             │
├─────────────────────────────────────────────────────────────┤
│  Internal:                                                  │
│  ├── combinations() - Recursive Cartesian product algorithm │
│  └── validateInput() - Input format validation              │
└─────────────────────────────────────────────────────────────┘

```

### Algorithm Overview

[](#algorithm-overview)

The generator uses a recursive algorithm to compute the Cartesian product:

1. **Input Validation** - Ensures all keys are non-numeric strings and all values are string arrays
2. **Value-to-Key Mapping** - Creates a reverse lookup map from values to their original keys
3. **Recursive Combination** - Builds combinations from the bottom up using recursion
4. **Key Restoration** - Maps generated combinations back to their original associative keys

📦 Installation
--------------

[](#-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/combinations) and [GitHub](https://github.com/baraja-core/combinations).

To install, simply use the command:

```
$ composer require baraja-core/combinations
```

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

### Requirements

[](#requirements)

- PHP 8.0 or higher

🚀 Basic Usage
-------------

[](#-basic-usage)

### Generating Combinations

[](#generating-combinations)

```
use Baraja\Combinations\CombinationGenerator;

$generator = new CombinationGenerator();

$input = [
    'format' => ['M', 'L'],
    'date' => ['2020', '2021'],
];

$combinations = $generator->generate($input);
```

**Input:**

```
[
    'format' => ['M', 'L'],
    'date' => ['2020', '2021'],
]
```

**Output:**

```
[
    ['format' => 'M', 'date' => '2020'],
    ['format' => 'M', 'date' => '2021'],
    ['format' => 'L', 'date' => '2020'],
    ['format' => 'L', 'date' => '2021'],
]
```

### Counting Combinations

[](#counting-combinations)

If you only need to know how many combinations will be generated (e.g., for validation or progress indication), use the `countCombinations()` method:

```
$generator = new CombinationGenerator();

$input = [
    'size' => ['S', 'M', 'L', 'XL'],
    'color' => ['red', 'blue', 'green'],
    'material' => ['cotton', 'polyester'],
];

$count = $generator->countCombinations($input);
// Returns: 24 (4 × 3 × 2)
```

This method is memory-efficient as it calculates the count without generating the actual combinations.

📖 Advanced Examples
-------------------

[](#-advanced-examples)

### Product Variant Generation

[](#product-variant-generation)

```
$generator = new CombinationGenerator();

$productOptions = [
    'size' => ['S', 'M', 'L', 'XL'],
    'color' => ['black', 'white', 'navy'],
    'sleeve' => ['short', 'long'],
];

$variants = $generator->generate($productOptions);
// Generates 24 product variants
```

### Test Matrix Generation

[](#test-matrix-generation)

```
$generator = new CombinationGenerator();

$testMatrix = [
    'browser' => ['chrome', 'firefox', 'safari'],
    'os' => ['windows', 'macos', 'linux'],
    'resolution' => ['1080p', '4k'],
];

$testCases = $generator->generate($testMatrix);
// Generates 18 test scenarios
```

### Single Dimension Input

[](#single-dimension-input)

The generator also handles single-dimension inputs correctly:

```
$generator = new CombinationGenerator();

$input = [
    'status' => ['active', 'inactive', 'pending'],
];

$result = $generator->generate($input);
// Returns: [['status' => 'active'], ['status' => 'inactive'], ['status' => 'pending']]
```

⚠️ Input Validation Rules
-------------------------

[](#️-input-validation-rules)

The generator enforces strict input validation to ensure correct operation:

### 1. Non-Numeric Keys Required

[](#1-non-numeric-keys-required)

All top-level keys must be non-numeric strings:

```
// Valid
$input = ['size' => ['S', 'M'], 'color' => ['red', 'blue']];

// Invalid - throws InvalidArgumentException
$input = [0 => ['S', 'M'], 1 => ['red', 'blue']];
$input = ['123' => ['S', 'M']];
```

### 2. Values Must Be Arrays

[](#2-values-must-be-arrays)

Each key must contain an array of values:

```
// Valid
$input = ['size' => ['S', 'M', 'L']];

// Invalid - throws InvalidArgumentException
$input = ['size' => 'M'];
```

### 3. All Values Must Be Strings

[](#3-all-values-must-be-strings)

Individual values within arrays must be strings:

```
// Valid
$input = ['year' => ['2020', '2021', '2022']];

// Invalid - throws InvalidArgumentException
$input = ['year' => [2020, 2021, 2022]];
```

### 4. Values Must Be Unique Across All Keys

[](#4-values-must-be-unique-across-all-keys)

All values across all keys must be unique. This is required for the reverse key mapping:

```
// Valid - all values are unique
$input = [
    'size' => ['small', 'medium', 'large'],
    'fit' => ['slim', 'regular', 'relaxed'],
];

// Invalid - 'M' appears in both keys
$input = [
    'size' => ['S', 'M', 'L'],
    'gender' => ['M', 'F'],
];
```

🔧 Error Handling
----------------

[](#-error-handling)

The generator throws `InvalidArgumentException` with descriptive messages for invalid inputs:

```
try {
    $generator = new CombinationGenerator();
    $combinations = $generator->generate($input);
} catch (\InvalidArgumentException $e) {
    // Handle validation errors
    echo "Invalid input: " . $e->getMessage();
}
```

### Common Error Messages

[](#common-error-messages)

- `"Section key must be non numeric key."` - A numeric key was used
- `"Section values must be array, but {type} given."` - A non-array value was provided
- `"Section item value must be a string, but {type} given."` - A non-string item in the value array
- `"Value {value} is not unique..."` - Duplicate value found across different keys

💡 Use Cases
-----------

[](#-use-cases)

- **E-commerce**: Generate all product variants (size, color, material combinations)
- **Testing**: Create test matrices for cross-browser/cross-platform testing
- **Configuration**: Enumerate all possible configuration combinations
- **Scheduling**: Generate time slot combinations (day, hour, room)
- **Data Analysis**: Create exhaustive scenario combinations for analysis
- **Form Generation**: Build dynamic form option combinations

👤 Author
--------

[](#-author)

**Jan Barášek** -

📄 License
---------

[](#-license)

`baraja-core/combinations` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/combinations/blob/master/LICENSE) file for more details.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance52

Moderate activity, may be stable

Popularity23

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 96% 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 ~25 days

Total

5

Last Release

1916d ago

Major Versions

v1.1.0 → v2.0.02021-02-09

PHP version history (3 changes)v1.0.0PHP &gt;=7.4.0

v1.1.0PHP ^7.4 || ^8.0

v2.0.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (24 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

combinationsmathphp

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/baraja-core-combinations/health.svg)

```
[![Health](https://phpackages.com/badges/baraja-core-combinations/health.svg)](https://phpackages.com/packages/baraja-core-combinations)
```

PHPackages © 2026

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