Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possibilities in 2d array

I have this array:

$array = array
(
    array('1', '2', '3'),
    array('!', '@'),
    array('a', 'b', 'c', 'd'),
);

And I want to know all character combination of sub arrays.. for example :

1!a
1!b
1!c
1!d
1@a
1@b
1@c
1@d
2!a
2!b
2!c
2!d
2@a
2@b
...

Currently I am having this code :

for($i = 0; $i < count($array[0]); $i++)
{
    for($j = 0; $j < count($array[1]); $j++)
    {
        for($k = 0; $k < count($array[2]); $k++)
        {
            echo $array[0][$i].$array[1][$j].$array[2][$k].'<br/>';
        }
    }
}

It works, but I think it is ugly, and when I am adding more arrays, I have to add more for. I am pretty sure there is a way to do this recursively, but I don't know how to start/how to do it. A little help could be nice!

Thanks you!

like image 284
Vallières Avatar asked Oct 14 '22 06:10

Vallières


1 Answers

You can create an recursive function like this:

function combination($array, $str = '') {
   $current = array_shift($array);
   if(count($array) > 0) {
       foreach($current as $element) {
           combination($array, $str.$element);
       }
   }
   else{
       foreach($current as $element) {
           echo $str.$element . PHP_EOL;
       }
   } 
}

Then:

combination($array);

If you want to have all combination in a new array, rather then to print them, extend the function like so:

function combination($array, array &$results, $str = '') {
   $current = array_shift($array);
   if(count($array) > 0) {
       foreach($current as $element) {
           combination($array, $results,  $str.$element);
       }
   }
   else{
       foreach($current as $element) {
           $results[] = $str.$element;
       }
   } 
}

$results = array();
combination($array, $results);
like image 167
Felix Kling Avatar answered Oct 20 '22 09:10

Felix Kling