Think of it as a n-bit integer, with each bit corresponding to whether a word is included or not in a given string in your array. Loop from 1 to (1 << n) - 1, which in this case is 1 to 15, to get your 15 word lists, and for each one, check each of the bits in the integer and add the corresponding word if the corresponding bit is set:
function getCombinations($sentence)
{
$words = explode(" ", $sentence);
$combinations = array();
for($i = 1; $i < (1 << count($words)); $i++)
{
$wordlist = "";
for($j = 0; $j < count($words); $j++)
{
if($i & (1 << $j))
{
$wordlist = $wordlist . " " . $words[$j];
}
}
array_push($combinations, substr($wordlist, 1));
}
return $combinations;
}
$a = "my name is john";
print_r(getCombinations($a));
If you want your strings to be sorted by the number of words, add an extra loop for the word counts:
for($wordcount = count($words); $wordcount >= 1; $wordcount--)
{
for($i = 1; $i < (1 << count($words)); $i++)
{
if(NumberOfSetBits($i) == $wordcount)
{
$wordlist = "";
// generate word list..
}
}
}
NumbeOfSetBits function from here