Find All Possible Combination Of An Array In PHP

Find All Possible Combination Of An Array In PHP

Today, one of the tasks involved at work required me to solve the problem outlined in the title of this post. For example, given an array of (‘red’, ‘blue’, ‘green’), we want to return the following:
red 
blue 
red blue 
green 
red green 
blue green 
red blue green
Initially my first impression was to use recursive function call, but it turned out to be quite complicated. After googling, Tom Butler has a very simple solution. I have modified it so that it will return an array of combinations:
public static function getQuestionCombinations($array)
{
    $return = array();

    $num = count($array);

    // The total number of possible combinations
    $total = pow(2, $num);

    // Loop through each possible combination
    for ($i = 0; $i < $total; $i++) {
        //For each combination check if each bit is set
        $data = array();
        for ($j = 0; $j < $total; $j++) {
           // Is bit $j set in $i?
            if (pow(2, $j) & $i) {
                $data[] = $array[$j];
            }
        }

        if($data) {
            $return[] = $data;
        }
    }

    return $return;
}
Tom has already explained in this post about the idea behind the function. This saved me heaps of time.

Leave a Reply

Your email address will not be published.

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!