Skip to content

Instantly share code, notes, and snippets.

@fancyweb
Created July 19, 2016 07:55
Show Gist options
  • Save fancyweb/e845834f3e4eedf902d1e9385271f7f9 to your computer and use it in GitHub Desktop.
Save fancyweb/e845834f3e4eedf902d1e9385271f7f9 to your computer and use it in GitHub Desktop.
<?php
// copyright josé 2002
/**
* @param array $array
*
* @return array
*/
public static function cartesianProduct(array $array)
{
$count = count($array);
if ($count <= 1) {
return $count > 0 ? array_map(function ($array) {
return array($array);
}, $array[0]) : $array;
}
$cartesianProduct = array();
$last = array_pop($array);
foreach ($last as $value) {
foreach (self::cartesianProduct($array) as $toAdd) {
$cartesianProduct[] = is_array($toAdd) ? array_merge($toAdd, array($value)) : array(
$toAdd,
$value
);
}
}
return $cartesianProduct;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment