Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,957 questions

51,899 answers

573 users

How to get all possible combinations from an array of numbers in PHP

1 Answer

0 votes
function GetCombinationsEqualToN($arr, $N, $combination) {
    $sum = 0;
        
    foreach ($combination as $num) {
        $sum += $num;
    }
        
    if ($sum == $N) {
        echo "sum(" . implode(", ", $combination) . ") = " . $N . "\n";
    }
        
    if ($sum >= $N) {
        return;
    }
        
    for ($i = 0; $i < count($arr); $i++) {
        $remaining = array();
        for ($j = $i + 1; $j < count($arr); $j++) {
            array_push($remaining, $arr[$j]);
        }

        $combination_next = [];
        foreach ($combination as $num) {
            $combination_next[] = $num;
        }
    array_push($combination_next, $arr[$i]);

    GetCombinationsEqualToN($remaining, $N, $combination_next);
    }
}

$arr = array(4, 6, 8, 2, 1, 10, 3, 5, 13);
        
$N = 13;
        
GetCombinationsEqualToN($arr, $N, array());
        



/*
run:

sum(4, 6, 2, 1) = 13
sum(4, 6, 3) = 13
sum(4, 8, 1) = 13
sum(4, 1, 3, 5) = 13
sum(6, 2, 5) = 13
sum(8, 2, 3) = 13
sum(8, 5) = 13
sum(2, 1, 10) = 13
sum(10, 3) = 13
sum(13) = 13

*/

 



answered Oct 15, 2022 by avibootz
edited Oct 15, 2022 by avibootz
...