Suppose I have a string, like so:
$string = 'president barack obama';
Now, suppose I want to explode this into an array, breaking at the words. You'd think I can just use explode()
, right? That works, but what if I want an array of all possible left-to-right combinations of the words? Like so:
Array
(
[0] => 'barack'
[1] => 'barack obama'
[2] => 'obama'
[3] => 'president'
[4] => 'president barack'
[5] => 'president barack obama'
)
What is the most efficient way to do this?
Possible solution:
I've come up with one possible solution so far, but I'm hoping one of you can give me a better idea. I imagine approaching this like so:
- Explode normally.
- Loop through each word.
- For each word, store it in an array. Then, check if there is another word in the array (after itself). If there is, add a new array value which consists of
$current_word . ' ' . $new_word;
. Do this for each word.
Now, that will probably work. However, it seems annoying, and I'm afraid someone else may have a better way of doing this. What do you all recommend? Is there, perhaps, a PHP function that does just this that I don't know about?