views:

101

answers:

1

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!

+4  A: 

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);
Felix Kling
How does this not break in PHP 5? I mean, it works...but why? I thought i remembered reading something about arrays and objects always getting passed by reference now...wouldn't that mean $array gets mangled?
cHao
Felix Kling