Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all possible combinations without duplicates

How can I get all the possible combinations of given numbers. For instance I have

$arr = [ 1, 2, 3, 4]

I want to get the combinations without any duplicates inside the combinations

[1] => [1]
[2] => [2]
[3] => [3]
[4] => [4]
[5] => [1, 2]
[6] => [1, 3]
[7] => [1, 4]
[8] => [2, 3]
[9] => [2, 4]
[10] => [3, 4]
[11] => [1, 2, 3]
[12] => [1, 2, 4]
[13] => [1, 3, 4]
[14] => [2, 3, 4]
[15] => [1, 2, 3, 4]
like image 448
Enthys Avatar asked May 23 '26 21:05

Enthys


1 Answers

I hope below function work as per your expected output :

function get_array_combination($arr) {
    $results = array(array( ));

    foreach ($arr as $values)
        foreach ($results as $combination)
                array_push($results, array_merge($combination, array($values))); // Get new values and merge to your previous combination. And push it to your results array
    return $results;
}
$set = array('1', '2', '3', '4');
$final_array = get_array_combination($set);
echo "<pre>";
print_r(array_values(array_filter($final_array))); // Removed blank entry from array and re indexing array keys.
like image 161
hardik solanki Avatar answered May 25 '26 12:05

hardik solanki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!