**This question is not a duplicate of the suggested question above.** The title may *sound* similar, but its answer does not in any way lead to the result described in the question below.

---

I'm having a hard time recursively iterating through an array of unknown length to create unique combinations of strings. Can you help?

The goal is to take a string like `foo bar` and create unique combinations from this string:

```
foo
bar
bar_foo (alphabetized to make unique combinations, not permutations)

```

Another example:

`car bar add` should return:

```
add
add_bar
add_car
add_bar_car
bar
bar_car
car

```

Here's my progress:

```
function string_builder($length) {
    $arrWords = array('add','bar','car','dew','eat','fat','gym','hey','ink','jet','key','log','mad','nap','odd','pal','qat','ram','saw','tan','urn','vet','wed','xis','yap','zoo');
    $arr = array();
    for ($i=0; $i < $length; $i++) { 
        $arr[] = $arrWords[$i];
    }
    return implode(' ', $arr);
}
function get_combinations($string) {
    $combinations = array(); // put all combinations here
    $arr = explode(' ',$string);
    $arr = array_unique($arr); // only unique words are important
    sort($arr); // alphabetize to make unique combinations easier (not permutations)
    $arr = array_values($arr); // reset keys
    for ($i=0; $i < count($arr); $i++) {
        // this is where I'm stuck
        // how do I loop recursively through all possible combinations of an array?
    }
    return $combinations;
}
// Test it!
for ($i=1; $i < 26; $i++) { 
    $string = string_builder($i);
    $combinations = get_combinations($string);
    echo $i . " words\t" . count($combinations) . " combinations\t" . $string . "\n";
    // print_r($combinations);
}

```

---

Another attempt:

```
function getCombinations2($str, $min_length = 2) {
    $words = explode(' ', $str);
    $combinations = array();
    $len = count($words);
    for ($a = $min_length; $a <= $min_length; $a++) {
        for ($pos = 0; $pos < $len; $pos ++) {
            if(($pos + $a -1) < $len) {
                $tmp = array_slice($words, $pos, $a);
                sort($tmp);
                $tmp = implode('_',$tmp);
                $combinations[] = $tmp;
            }
        }
    }
    $combinations = array_unique($combinations);
    return $combinations;
}

```

You can know you're successful when you print out the combinations and look for a couple combinations that should be there (for example, "fat\_zoo","car\_tan"). Both of my attempts will show several of these, but never all of them.