Joined October 2012
·

Aaron Ott

Thornton, CO
·
·
·

Posted to Reverse words in a sentence - PHP over 1 year ago

What about using recursion. I like it because of it's elegance.

$str = "The lazy dog jumped over the fox";

function flip_words($str) {
  $last_space = strrpos($str, " ");
  if ($last_space === FALSE) {
    echo " $str";
  }
  else {
    echo substr($str, $last_space);
    flip_words(substr($str, 0, $last_space));
  }
}

flip_words($str);
Achievements
175 Karma
6,805 Total ProTip Views