Recursive approach:
function iterate($words) { if(($total = count($words)) > 0) { $str = ''; for($i = 0; $i < $total; $i++ ) { $str .= ' ' . $words[$i]; echo $str . PHP_EOL; } array_shift($words); iterate($words); } } $text = "Today is a great day."; $words = str_word_count($text, 1); iterate($words);
The foregoing will only consider words. It will not remove duplicates. Numbers are not words, and punctuation is not. Given a five-word test sentence, the recursive approach is negligible faster than the array_splice solution. However, this increases significantly with each additional word. A quick test on my car with a ten-word sentence ended in almost half the time.
Disclaimer: Isolated tests depend on a number of factors and may produce different results on different machines. In any case, they can provide an indicator of code performance (often in the field of microrecovery), but nothing more.
Gordon
source share