PHP: How do you generate all possible combinations of values ​​in an array?

Possible duplicate:
which will take numbers or words and find all possible combinations

If I have an array, for example:

array('a', 'b', 'c', 'd'); 

How to create a new array with all possible combinations of these 4 values, such as

 aaaa, aaab, aaac, aaad ... dddb, dddc, dddd 

Thanks!

+6
source share
2 answers

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!

+9
source

You must use a recursive function

 function perm($arr, $n, $result = array()) { if($n <= 0) return false; $i = 0; $new_result = array(); foreach($arr as $r) { if(count($result) > 0) { foreach($result as $res) { $new_element = array_merge($res, array($r)); $new_result[] = $new_element; } } else { $new_result[] = array($r); } } if($n == 1) return $new_result; return perm($arr, $n - 1, $new_result); } $array = array('a', 'b', 'c', 'd'); $permutations = perm($array, 4); print_r($permutations); 
+4
source

All Articles