views:

67

answers:

1

I am trying to take a string and display the possible combinations of it (in PHP), but while saying in order of each word. For example: "how are you" would return (an array)

How are you
How are
are you
how
you
are

The code I have now displays all combinations but I am wanting it to keep them in order and not flip words. Any one have any ideas or snippets they care to share? Thanks

+1  A: 

Set two iterators and print everything between them. So something like this:

<?
$str = "How are you";
$words = explode(" ",$str);
$num_words = count($words);
for ($i = 0; $i < $num_words; $i++) {
  for ($j = $i; $j < $num_words; $j++) {
    for ($k = $i; $k <= $j; $k++) {
       print $words[$k] . " ";
    }
    print "\n";
  }
}
?>

EDIT Few minor errors

Output


How 
How are 
How are you 
are 
are you 
you 
Jamie Wong
Inefficencies abound!$str = "How are you";$words = explode(" ",$str);$total_words = count($words);for ($i = 0; $i < $total_words; $i++) { for ($j = $i+1; $j < $total_words; $j++) { for ($k = $i; $k < $j; $k++) { print $words[k] . " "; } print "\n"; }}
Marco Ceppi
@Marco Good Point - Fixed
Jamie Wong
Works great! Thank you.
mikelbring
If you don't want the extraneous space and want the result to be an array, just `push` the `$words[$k]` into an array then `implode` it, adding the result to the array to be returned.
Jamie Wong