# How to Create All Possible Word Combinations from a String With PHP

By | August 4, 2008

Sometimes you need to change the word order in a line for some reason. I am going to show you a PHP solution that allows you to create all possible word combinations from a string. The code below should explain you all operations that are performed.

<?

// Factorial
function fact(\$s){
if (\$s==0) return 1;
else return \$fact = \$s * fact(\$s-1);
}

// Let’s count the number of words by creating an array
\$words=explode(” “, \$phrase);
\$n=count(\$words);

// Here comes a loop that creates all possible combinations of array positions
for (\$m=1; \$m<=fact(\$n); \$m++)
{
\$ken = \$m-1;
\$f = 1;
\$a = array();
for(\$iaz=1; \$iaz<=\$n; \$iaz++)
{
\$a[\$iaz] = \$iaz;
\$f = \$f*\$iaz;
}
for(\$iaz=1; \$iaz<=\$n-1; \$iaz++)
{
\$f = \$f/(\$n+1-\$iaz);
\$selnum = \$iaz+\$ken/\$f;
\$temp = \$a[\$selnum];
for(\$jin=\$selnum; \$jin>=\$iaz+1; \$jin–)
{
\$a[\$jin] = \$a[\$jin-1];
}
\$a[\$iaz] = \$temp;
\$ken = \$ken%\$f;
}
\$t=1;

// Let’s start creating a word combination: we have all the necessary positions
\$newphrase=””;

// Here is the while loop that creates the word combination
while (\$t<=\$n)
{
\$newphrase.=\$words[\$a[\$t]-1].” “;
\$t++;
}
// Output of the phrase
echo \$newphrase.”rn”;

}

?>

The example above will output:

Phrase Comes Here Your
Phrase Here Comes Your
Comes Phrase Here Your
Comes Here Phrase Your
Here Phrase Comes Your
Here Comes Phrase Your

You can play with number combinations instead of words.

## 3 thoughts on “How to Create All Possible Word Combinations from a String With PHP”

1. Gabriel

Very good algorithm.

I think i will use it to output some words for tags combinations and modify it a little bit to fit my needs. This code will output the combinations with all words. I need it to output all possible combinations comparing all words.

example:
Your

By the way, add another ‘-‘ (minus) in this line:
for(\$jin=\$selnum; \$jin>=\$iaz+1; \$jin–)

Nice job, thanks.

2. Gabriel

Very good algorithm.

I think i will use it to output some words for tags combinations and modify it a little bit to fit my needs. This code will output the combinations with all words. I need it to output all possible combinations comparing all words.

example:
Your
3. GiN