How to print all possible unique combinations of array in PHP

1 Answer

0 votes
function getUniqueCombinations($arr, $min = 1, $max = 100) {
    $words_count = count($arr);
    $combinations_count = pow(2, $words_count);

    $combinations_arr = array();
    for ($i = 0; $i < $combinations_count + 1; $i++) {
        // 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
        $binary_number = sprintf("%0" . $words_count . "b", $i); 
        $one_combination_arr = array();
        for ($j = 0; $j < $words_count; $j ++) {
            $binary_number{$j} == '1' and $one_combination_arr[] = $arr[$j];
        }

        count($one_combination_arr) >= $min && count($one_combination_arr) <= $max 
                                       and $combinations_arr[] = $one_combination_arr;
        }
    return $combinations_arr;
}

$arr = array("php", "java", "c++", "python");

$combinations_arr = getUniqueCombinations($arr);

sort($combinations_arr);

print_r(array_map(function($s) { return implode(", ", $s); }, $combinations_arr));

 
 
 
 
/*
run:
 
Array
(
    [0] => c++
    [1] => java
    [2] => php
    [3] => php
    [4] => python
    [5] => c++, python
    [6] => java, c++
    [7] => java, python
    [8] => php, c++
    [9] => php, java
    [10] => php, python
    [11] => java, c++, python
    [12] => php, c++, python
    [13] => php, java, c++
    [14] => php, java, python
    [15] => php, java, c++, python
)

*/

 



answered Jun 26, 2021 by avibootz
edited Jun 27, 2021 by avibootz
...