1

I have the nested array structure below.

$letters = array(
    $A = array(1,2),
    $B = array(3,4),
    $C = array(5,6)
);

My goal is to find all possible permutations of the numbers, while the letters must keep the order A-B-C. The expected output is:

1-3-5
1-3-6
1-4-5
1-4-6
2-3-5
2-3-6
2-4-5
2-4-6

Of course, this could easily be accomplished with foreach:

foreach($A as $a){
    foreach($B as $b){
        foreach($C as $c){
            echo $a.$b.$c.'<br>';
        }
    }
}

However, I want this to work dynamically, with a varying number of arrays. I already figured that a recursive approach could work, but I cannot wrap my head around it. Can someone help?

1
  • Your $letters array looks weird. Wouldn't $letters = array(array(1, 2), array(3, 4), array(5, 6)); be enough? Commented Feb 13, 2019 at 13:46

1 Answer 1

3

Simply pass the string along into recursions:

function work($str, $arr, $i)
{
    $last = ($i == count($arr) - 1);
    foreach ($arr[$i] as $c)
    {
        if ($last)
            echo $str . $c . "\n"; // print whole line
        else
            work($str . $c, $arr, $i + 1); // recurse to next column
    }
}

$letters = array(
    array(1,2),
    array(3,4),
    array(5,6)
);

work("", $letters, 0);

produces

135
136
145
146
235
236
245
246

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.