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.
1 2 3 4 5 6 7 |
<?php //Declare string variable $myStr = "Welcome to TutorialDeep!"; //Reverse string using strrev() echo strrev($myStr); ?> |
Output
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:
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare string variable $myStr = "Welcome to TutorialDeep!"; //Reverse string without using strrev() $myStrRevert= implode(array_reverse(str_split($myStr))); //Print reverted string echo $myStrRevert; ?> |
Output
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php //Declare string variable $myStr = "Welcome to TutorialDeep!"; //Find length of string $Strlength = strlen($myStr); //Reverse and Print string without using strrev() for($i=$Strlength -1;$i >=0;$i--){ echo $myStr[$i]; } ?> |
Output
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