Finding cartesian product with PHP associative arrays
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Cartesian products with associative arrays are common in configuration generation, feature matrix testing, and variant pricing. The main risk is explosive growth in result count and memory use. A practical implementation should be clear, deterministic, and able to switch to streaming when combinations become large.
Define Input and Output Contract
Input shape usually looks like keyed arrays of options:
Expected output is an array of associative rows, each containing one value per key.
Iterative Cartesian Product Implementation
A loop-based approach is easy to follow and maintain.
This method is deterministic if source key order is deterministic.
Estimating Result Size Early
Before generating combinations, compute estimated size.
If estimate is too high, avoid full materialization.
Generator-Based Streaming Alternative
For large spaces, use generators to emit rows one by one.
This keeps memory usage lower and supports early termination.
Pruning Invalid Combinations
In real systems, many combinations are invalid. Prune early instead of filtering the final full output.
For example, skip invalid pairs while generating, not after storing all rows. Early pruning gives major performance gains when constraints are strict.
Practical Use in Web Applications
Common production patterns:
- Build variant combinations for product configuration.
- Generate test cases for form permutations.
- Expand deployment matrix from environment options.
For web endpoints, cap maximum generated rows and return clear error when limits are exceeded to protect server resources.
Testing Recommendations
Example Size Guard
Before generating combinations in web requests, enforce a hard upper limit.
This simple check prevents memory spikes and keeps API latency predictable when users submit high-cardinality option sets.Test with:
- Empty option map.
- Single-key options.
- Keys with one value each.
- Constraint-pruned paths.
Also verify output key order if downstream consumers depend on deterministic serialization.
Preserving Deterministic Key Order
If output rows feed snapshot tests, keep associative key order stable before encoding. A simple ksort on each row can make serialized output deterministic across environments and reduce flaky test diffs.
Apply this only when canonical ordering is required by consumers.## Common Pitfalls
- Overwriting partial rows instead of expanding from all current rows.
- Ignoring exponential growth and crashing memory.
- Filtering invalid combinations only after full generation.
- Assuming key iteration order is stable across environments.
- Returning massive payloads without response size limits.
Summary
- Cartesian product generation is straightforward but grows quickly.
- Loop-based expansion is clear for moderate input sizes.
- Generator-based approach is safer for large combination spaces.
- Estimate size and apply pruning before heavy processing.
- Enforce operational limits when exposing results through APIs.
Related reading
- Finding centre of rotation for a set of points
- Finding common elements in two arrays of different size
- finding common prefix of array of strings
- Finding Contiguous Areas of Bits in 2D Bit Array
- Finding dictionary words
- Finding duplicates in On time and O1 space
- Finding first non-repeating number in integer array
- Finding height in Binary Search Tree

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.