PHP
Generate Cartesian Product of Multiple Arrays
Discover how to create all possible combinations (Cartesian product) from several PHP arrays, useful for generating permutations, product variations, or comprehensive test cases.
<?php
function cartesianProduct(array ...$arrays): array
{
$result = [[]]; // Start with an array containing an empty array
foreach ($arrays as $key => $array) {
$temp = [];
foreach ($result as $resultItem) {
foreach ($array as $item) {
$temp[] = array_merge($resultItem, [$item]);
}
}
$result = $temp;
}
return $result;
}
$colors = ['red', 'blue'];
$sizes = ['S', 'M', 'L'];
$materials = ['cotton', 'polyester'];
$productVariations = cartesianProduct($colors, $sizes, $materials);
/*
Example Output:
[
["red", "S", "cotton"],
["red", "S", "polyester"],
["red", "M", "cotton"],
["red", "M", "polyester"],
["red", "L", "cotton"],
["red", "L", "polyester"],
["blue", "S", "cotton"],
["blue", "S", "polyester"],
["blue", "M", "cotton"],
["blue", "M", "polyester"],
["blue", "L", "cotton"],
["blue", "L", "polyester"]
]
*/
// Example with associative arrays
$options1 = [['id' => 1, 'name' => 'Color Red'], ['id' => 2, 'name' => 'Color Blue']];
$options2 = [['id' => 10, 'name' => 'Size S'], ['id' => 11, 'name' => 'Size M']];
$combinedOptions = cartesianProduct($options1, $options2);
/*
Example Output for combinedOptions (simplified):
[
[ ["id" => 1, "name" => "Color Red"], ["id" => 10, "name" => "Size S"] ],
[ ["id" => 1, "name" => "Color Red"], ["id" => 11, "name" => "Size M"] ],
[ ["id" => 2, "name" => "Color Blue"], ["id" => 10, "name" => "Size S"] ],
[ ["id" => 2, "name" => "Color Blue"], ["id" => 11, "name" => "Size M"] ]
]
*/
How it works: This snippet provides a `cartesianProduct` function to generate all possible combinations from a list of input arrays. It iteratively combines elements from each array with the existing combinations, building up a complete set of permutations. This is extremely valuable for scenarios like generating product variations, exhaustive test cases, or exploring all possible states.