There is an array like this (for the convenience of the example, I show only 3 keys, abc), in fact, there are much more keys.

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

At the output you need to get this, a prerequisite is that the values ​​were only 3-character.

 Array( [0] => aaa [1] => aab [2] => aac [3] => aba [4] => abb [5] => abc [6] => aca [7] => acb [8] => acc [9] => baa [10] => bab [11] => bac [12] => bba [13] => bbb [14] => bbc [15] => bca [16] => bcb [17] => bcc [18] => caa [19] => cab [20] => cac [21] => cba [22] => cbb [23] => cbc [24] => cca [25] => ccb [26] => ccc) 

    2 answers 2

    You can use a recursive approach. The function below will generate combinations of any specified length from any array.

     function combine($source, $max_len = 3, $key_part = '') { $result = []; foreach ($source as $value) { if (strlen($key_part.$value) >= $max_len) { $result[] = substr($key_part.$value, 0, $max_len); } else { $result = array_merge($result, combine($source, $max_len, $key_part.$value)); } } return $result; } 

    Using

     $array = array('a', 'b', 'c', 'd'); $keys = combine($array, 3); echo '<pre>'.print_r($keys, 1).'</pre>'; $array = array('a', 'b'); $keys = combine($array, 6); echo '<pre>'.print_r($keys, 1).'</pre>'; 

    UPD: Added $ trim argument - you can specify characters in it, which should not be at the beginning or end of the key

     function combine($source, $max_len = 3, $trim = '', $key_part = '') { $result = []; foreach ($source as $value) { if (strlen($key_part.$value) >= $max_len) { if (!strlen($trim) || $key_part.$value == trim($key_part.$value, $trim)) { $result[] = substr($key_part.$value, 0, $max_len); } } else { $result = array_merge($result, combine($source, $max_len, $trim, $key_part.$value)); } } return $result; } $array = array('a', 'b', 'c', '-', '+'); $keys = combine($array, 3, '-+'); echo '<pre>'.print_r($keys, 1).'</pre>'; 
    • It looks like your code works, only in my $ result = []; - a mistake, maybe it should be? $ result [] = ''; Or not? And there are empty values ​​in the keys, how to remove them? Can I understand with them 100% working code? - skillful
    • So you have an older version of php. Replace $result = []; on $result = array(); - Darevill
    • There can be no empty values. Unless you added $result[] = ''; , then this is the empty value - Darevill
    • Yes, then everything is great! - skillful
    • I have one more question for you, I hope you can ask you here personally. In the array $ array = array ('a', 'b', 'c', 'd'); instead of 'd' is a tyre sign '-'. It is necessary to change your recursive code so that at the edges there is no tyre. For example, these values ​​are not correct and are deleted: -00v; 000-; -00- - skillful

    We generate an array, where all the combinations and shuffle (mixes).