Skip to content

Instantly share code, notes, and snippets.

@phcorp
Last active February 3, 2024 13:14
Show Gist options
  • Save phcorp/c18b1d3bcb87ff75e5edeb014340d73d to your computer and use it in GitHub Desktop.
Save phcorp/c18b1d3bcb87ff75e5edeb014340d73d to your computer and use it in GitHub Desktop.
Cartesian product
<?php
function multiply(...$sets): array
{
if (!$sets) {
return [[]];
}
$set = array_shift($sets);
$products = multiply(...$sets);
$result = [];
foreach ($set as $value) {
foreach ($products as $product) {
array_unshift($product, $value);
$result[] = $product;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment