Skip to content

Instantly share code, notes, and snippets.

@wlkns
Last active February 16, 2023 07:44
Show Gist options
  • Save wlkns/025b13763745fa2c99a4a20d903410b0 to your computer and use it in GitHub Desktop.
Save wlkns/025b13763745fa2c99a4a20d903410b0 to your computer and use it in GitHub Desktop.
Generate unique combinations of PHP arrays
<?php
/**
* Generate unique combinations of an array...
*/
function combinations($array)
{
$return = [];
$num = count($array);
// The total number of possible combinations
$total = pow(2, $num);
// Loop through each possible combination
for ($i = 0; $i < $total; $i++) {
//For each combination check if each bit is set
$data = array();
for ($j = 0; $j < $total; $j++) {
// Is bit $j set in $i?
if (pow(2, $j) & $i) {
$data[] = $array[$j];
}
}
if(count($data)) {
array_push($return, $data);
}
}
return $return;
}
/**
* Generate numeric combinations as arrays e.g. [[3,2,1], [2,1], [2,3], [1,3],...]
*/
function numeric_combinations($count)
{
$return = [];
// The total number of possible combinations
$total = pow(2, $count);
// Loop through each possible combination
for ($i = 0; $i < $total; $i++) {
//For each combination check if each bit is set
$data = array();
for ($j = 0; $j < $total; $j++) {
// Is bit $j set in $i?
if (pow(2, $j) & $i) {
$data[] = $j;
}
}
if(count($data)) {
array_push($return, $data);
}
}
return $return;
}
$data = ['a','b','c'];
$combinations = numeric_combinations(count($data));
array_map(fn($combination) => array_map(fn($idx) => $data[$idx], $combination), $combinations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment