Finding all word combinations from an array of words?


#1

I'm drawing a blank on this. I think I need to eat lunch hah.

If I have an array

$words = array('red', 'blue', 'green');

I would like to list all possible combinations of words. The results should be (in no particular order)

red
red blue
red blue green
red green
blue
blue green
green

Note, I don't want to list the words in various orders, ("red blue green" and "red green blue" should both not be listed). Any help with this? I can't even think of what to search for to try and find help myself. Today is one of those days...


#2

Let :google: be your friend.

This example code might help.


#3

Fairly simple using a binary count:

<?php
$words = array('red', 'blue', 'green');
$num = count($words);

//The total number of possible combinations
$total = $num * $num;

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




#4

I did use Google and came across that before I posted here.That sample's results are incorrect for me though. It doesn't include the phrase "How you" in their example. I tried the code myself and it also was not correct. I then posted here because I didn't know what other phrases to type into google hah.


#5

Thanks! That works as needed!!


#6

now can this be done using array functions? I can get it say
red
red blue
blue green
green