Question

I am trying to put this code in a more flexible manner so it can work whatever the size of $sets array is. I suppose it can be done with recursion but cannot find the correct php syntax.

$sets = array(
                array(0, 1, 2, 3),
                array(0, 1, 2, 3),
                array(0, 1, 2, 3),
                array(0, 1, 2, 3)
                );

$combinations = array();

foreach($sets[0] as $s1)
    foreach($sets[1] as $s2)
        foreach($sets[2] as $s3)
            foreach($sets[3] as $s4)
                $combinations[] = array($s1, $s2, $s3, $s4);

print_r($combinations);
Was it helpful?

Solution

You can do it in recursion like this. The output is identical to your loops

<?php
$sets = array(
    array(0, 1, 2, 3),
    array(0, 1, 2, 3),
    array(0, 1, 2, 3),
    array(0, 1, 2, 3)
);

function get_combinations($sets, &$combinations = array(), &$row = array()) {
    if (count($sets) == 0) {
        $combinations[] = $row;
        return $combinations;
    }
    foreach ($sets[0] as $s) {
        $row[] = $s;
        get_combinations(array_slice($sets, 1), $combinations, $row);
        array_pop($row);
    }
    return $combinations;
}

$combinations = get_combinations($sets);

print_r($combinations);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top