How to Reverse Words in String in PHP Without strrev

Last Updated on May 14, 2021 by Roshan Parihar

In this tutorial, learn how to reverse words in a string using PHP. The short answer is to use the strrev() of PHP and pass the string variable as an argument.

However, you can also use other method given here that is useful to reverse a string without strrev(). Let’s find out with the examples given below here to learn the methods.

Method 1: How to Reverse Words in a String Using strrev() in PHP

The simple way to reverse the words in a string is by using the strrev() of PHP. It takes a single argument that is the string variable to pass. See the example below to get the idea of using the function.

Output

!peeDlairotuT ot emocleW

The output shows the reversed words that are the result of using the function.

Method 2: Reverse Words in a String Without Using strrev()

You can also reverse the words without using the strrev() function of PHP.

To revert the words of a string, you have to first split the string convert into an array using str_split() function. Furthermore, use the array_reverse() function to reverse the array data. After that, use the implode() function to convert the array into a string. The output is the reversed string as given below:

Output

!peeDlairotuT ot emocleW

The above example shows the same output as you get with the strrev(). However, it reversed the words of a string without using the strrev().

Method 3: Using For Loop of PHP

In addition to the above all methods, you can also reverse the words of a string using the for loop. To get the idea of using the loop, you can check the example given below:

Output

!peeDlairotuT ot emocleW

The output shows the reversed string and it gives the required result without using any type of functions of PHP. However, it takes few more seconds to run the loop and gives the output.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.