Posted on Leave a comment

How to flip the words in a sentence backwards with PHP

How do you flip the words in a sentence backwards with PHP?

This is one of those tests programmers like to give in interviews, at first it seems like you could just use the strrev() function, but it actually reverses the characters in a string which makes the words all show up backwards and so would only work for sentences made of palindromes. The actual answer is to blow the string up into an array of words using the explode() function, then reverse the order of the array with the array_reverse function, then use the implode()  function to glue the array back into a string.

The code looks like this:

I hope this is useful to you. Good luck in that interview.