Skip to content

Instantly share code, notes, and snippets.

@alixcan
Created May 14, 2017 08:23
Show Gist options
  • Save alixcan/47561ee492c1bd517fe0a4ccc2b66b7f to your computer and use it in GitHub Desktop.
Save alixcan/47561ee492c1bd517fe0a4ccc2b66b7f to your computer and use it in GitHub Desktop.
PHP array combinations
<?php
function combinations($arrays, $i = 0) {
if (!isset($arrays[$i])) {
return array();
}
if ($i == count($arrays) - 1) {
return $arrays[$i];
}
// get combinations from subsequent arrays
$tmp = combinations($arrays, $i + 1);
$result = array();
// concat each array from tmp with each element from $arrays[$i]
foreach ($arrays[$i] as $v) {
foreach ($tmp as $t) {
$result[] = is_array($t) ?
array_merge(array($v), $t) :
array($v, $t);
}
}
return $result;
}
//combinations(array $a1, array $a2, ...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment