Here is another way.
This function increases in the database ([number of elements in the array])
and uses the strtr function to replace characters for strings.
function everyCombination($array) { $arrayCount = count($array); $maxCombinations = pow($arrayCount, $arrayCount); $returnArray = array(); $conversionArray = array(); if ($arrayCount >= 2 && $arrayCount <= 36) { foreach ($array as $key => $value) { $conversionArray[base_convert($key, 10, $arrayCount)] = $value; } for ($i = 0; $i < $maxCombinations; $i++) { $combination = base_convert($i, 10, $arrayCount); $combination = str_pad($combination, $arrayCount, "0", STR_PAD_LEFT); $returnArray[] = strtr($combination, $conversionArray); } return $returnArray; } echo 'Input array must have between 2 and 36 elements'; }
Then...
print_r(everyCombination(array('a', 'b', 'c', 'd')));
It also seems significantly faster than the recursive example below.
Using microtime () on my server runs in 0.072862863540649 seconds
Below is a recursive example: 0.39673089981079 seconds.
138% faster!
source share