user1926784 user1926784 - 1 year ago 81
PHP Question

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

Possible Duplicate:

algorithm that will take numbers or words and find all possible combinations

If I have an array such as:

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

How would I create a new array with all possible combinations of those 4 values such as

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


Answer Source

Here's another way.

This function increments in base( [number of elements in array] )

and uses the strtr function to swap out the 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')));

This also seems to be significantly faster than the recursive example below.

Using microtime() on my server this code runs in 0.072862863540649 seconds

The recursive example below takes 0.39673089981079 seconds.

138% faster!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download