Hello! At the input we have the string "abc", as the output to get an array:

[0] => abc [1] => a,bc [2] => ab,c [3] => a,b,c 

The row size is unknown in advance. Thank you in advance!

UPD: Gentlemen, I apologize for the lack of clarity. I will clarify:

At the entrance:

"abcdef"

At the exit:

 [0] => abcdef [1] => a,bcdef [2] => ab,cdef [3] => abc,def [4] => abcd,ef [5] => abcde,f [6] => a,b,cdef [7] => a,b,c,def [8] => a,b,c,d,ef [9] => a,b,c,d,e,f [10] => ab,cdef [11] => ab,c,def [12] => ab,c,d,ef [13] => ab,c,d,e,f ... [n] => abc,d,e,f ... [n] => a,bcd,ef [n] => a,bcd,e,f ... [n] => abc,de,f ... [n] => a,bcde,f ... 

In general, all possible options where you can insert a comma between the letters

    2 answers 2

    Want recursion? You are welcome:

     function f($a) { $result = array(); if (strlen($a) <= 1) { $result[] = $a; } else { $first = substr($a, 0, 1); $tail = substr($a, 1); $arr = f($tail); // <<<=== Рекурсия здесь. foreach ($arr as $v) $result[] = $first . $v; foreach ($arr as &$v) $result[] = $first . ',' . $v; } return $result; } // Проверка. foreach (array('', 'a', 'ab', 'abc', 'abcd', 'abcde') as $str) { echo('<hr>'); foreach (f($str) as $s) echo($s . '<br>'); } 

    Output for abc :

     abc a,bc ab,c a,b,c 
    • Fine! this is what you need. Recursion was not necessary, I just do not see a solution without it - Maxim Tsarev

    There is no need for recursion, it is better to use it as a last resort, it is tighter cycles.

     $str = 'abcdefg'; $result[] = $str; $str2 = implode(',', str_split($str)); for ($i = 0; $i < strlen($str2)-1; $i+=2) { $index = strpos($str2, ',', $i); $result[] = substr($str2, 0, $index) . substr($str2, $index+1, strlen($str2)); } $result[] = $str2; var_dump($result); exit; 

    Conclusion:

     array(7) { [0]=> string(12) "ab,c,d,e,f,g" [1]=> string(12) "a,bc,d,e,f,g" [2]=> string(12) "a,b,cd,e,f,g" [3]=> string(12) "a,b,c,de,f,g" [4]=> string(12) "a,b,c,d,ef,g" [5]=> string(12) "a,b,c,d,e,fg" [6]=> string(13) "a,b,c,d,e,f,g" } 
    • It seems to me that your solution does not reflect the author’s tasks: abcdef => a, bcdef; ab, cdef; abc, def; abcd, ef; abcde, f; a, b, cdef; ... - Stanislav
    • mean direction? - KeyGenQt 2:22 pm
    • $ result [] = str_replace ('-', ',', str_replace (',', '', substr ($ str2, 0, $ index) .'- '. substr ($ str2, $ index + 1, strlen ($ str2)))); - KeyGenQt 2:26 pm
    • array (4) {[0] => string (3) "abc" [1] => string (4) "a, bc" [2] => string (4) "ab, c" [3] => string (5) "a, b, c"} - KeyGenQt 2:26 pm
    • There is nothing difficult to deploy - KeyGenQt