Skip to content

Instantly share code, notes, and snippets.

@bdelespierre
Created February 8, 2018 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdelespierre/0980c0f93cc63b883376a65865f44017 to your computer and use it in GitHub Desktop.
Save bdelespierre/0980c0f93cc63b883376a65865f44017 to your computer and use it in GitHub Desktop.
Array cartesian product
<?php
function array_cartesian_product(...$items): array
{
if (empty($items)) {
return [];
}
if (count($items) == 1) {
foreach ((array) $items[0] as $value) {
$result[] = (array) $value;
}
} else {
foreach ((array) $items[0] as $value) {
foreach (array_cartesian_product(...array_slice($items, 1)) as $values) {
array_unshift($values, $value);
$result[] = $values;
}
}
}
return $result ?? [];
}
$values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace'];
$colors = ["Hearts", "Tiles", "Clovers", "Spades"];
$cards = array_map('implode', array_cartesian_product($values, ' of ', $colors));
shuffle($cards);
var_dump(array_pop($cards));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment