-2

I have an Array with String values and want to combine these. Example Array:

Array("a", "b", "c");

Now I want an Array with all combinations of this String values in it. For this example:

Array("abc", "acb", "bac", "bca", "cab", "cba");

Each value should be included exactly one time. The problem is, that the length of this array is variable :-(

I tried it so far with many foreach and for constructs but did not get the solution yet. I want to built a method like

function combineArrayValues ($arr)

I hope somebody can give me a hint, how to randomly combine the String and get all possible combinations for an Array with any length. Thank you!

Best Regards,

Richard

Richard
  • 2,840
  • 3
  • 25
  • 37

1 Answers1

1

You can use this function to get all combinations of array values,

function combinevalues($items, $perms = array()) {
    if (empty($items)) { 
        echo join(' ', $perms) . "<br />";
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             combinevalues($newitems, $newperms);
         }
    }
}

$arr = array('a', 'b', 'c');

var_dump(combinevalues($arr));
US-1234
  • 1,519
  • 4
  • 24
  • 61