PHP

Generate Cartesian Product of Multiple PHP Arrays

Efficiently generate all possible combinations (Cartesian product) from several PHP arrays, useful for product variations or test data generation.

function cartesian_product(array ...$arrays): array {
    if (empty($arrays)) {
        return [[]];
    }

    $result = [[]];
    foreach ($arrays as $key => $array) {
        if (empty($array)) {
            // If any array is empty, the Cartesian product is empty
            return [];
        }
        $temp = [];
        foreach ($result as $prevCombination) {
            foreach ($array as $item) {
                $temp[] = array_merge($prevCombination, [$item]);
            }
        }
        $result = $temp;
    }
    return $result;
}

$colors = ['red', 'blue'];
$sizes = ['S', 'M', 'L'];
$materials = ['cotton', 'polyester'];

$productVariations = cartesian_product($colors, $sizes, $materials);

foreach ($productVariations as $variation) {
    echo implode(' ', $variation) . "
";
}

/* Expected 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
*/
How it works: This `cartesian_product` function generates all possible combinations from a variable number of input arrays. It iteratively builds up the result by taking each existing combination and appending every item from the next input array. This process effectively creates a 'cross-product' of the elements. It's highly useful in scenarios like generating all product variations based on different attributes (colors, sizes, materials) or creating comprehensive test case data where every combination of parameters needs to be covered.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs