This question already has an answer here:
I’m aware of several questions covering this topic (e.g. here), but none of them (at least from what I found) do what I need.
Say I have an array of 3 elements [1, 2, 3]
. I need to find all the possible unique combinations (so excluding permutations, like here), including the ones of repeating elements. So the result should be:
[1]
[2]
[3]
[1, 1]
[1, 2]
[1, 3]
[2, 2]
[2, 3]
[3, 3]
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 2, 3]
[1, 3, 3]
[2, 2, 2]
[2, 2, 3]
[2, 3, 3]
[3, 3, 3]
Excluding subsets like [3, 2, 1]
or [2, 1, 3]
, that are the same thing as [1, 2, 3]
.
How can I achieve this?
</div>
Fast solution using recursion, probably not the best way to do it, but it gets the job done.
<?php
$arr = array(1,2,3);
$result = array();
function combinations($arr, $level, &$result, $curr=array()) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
// TEST
foreach ($result as $arr) {
echo join(" ", $arr) . '<br>';
}
?>