In this post, we will learn how to reverse a string in PHP. There are two methods to reverse a string in PHP. First method is using strrev() function and Second method is without using strrev() function. In this Second method we use custom function for reverse a string. We will further learn to reverse string using both methods.


How To Reverse A String in PHP ?


Method 1 : Reverse A String in PHP using strrev() Function

In this method we will use PHP in-built strrev() string function for reverse a string. For this we follow the code given below:

<?php
$str = "CodexRadar";
echo strrev($str);
?> code-box

Output :
radaRxedoC

This is very easiest and simplest method to reverse a string in PHP.


Method 2 : Reverse A String in PHP using Custom Function

To get a reverse string we can also use custom function. For this, we follow the following step:
  1. First declare a variable to hold the reverse string.
  2. Then calculate the string length using the strlen() string function. To get the actual length of a string, subtract one from it.
  3. Then run for loop with appropriate conditions and concatenate the string inside the loop and store it in a variable.
  4. Then return this variable.
One more thing is important that when we assign the string to a variable. Then we can extract the character of this string using array method. This is very important concept. So always keep this in mind. We can see this in below example:

<?php
$str = "CodexRadar";
echo $str[0];
?> code-box

Output :
$str[0] give output "C",
$str[1] give output "o" and so on.

The complete code for reverse a string in PHP using custom function is given below:

<?php
$str = "CodexRadar";
echo getRevStr($str);
function getRevStr($inputStr) {
$revStr = "";
$count = strlen($inputStr) - 1;
for($i = $count; $i >= 0; $i--) {
$revStr.=$inputStr[$i];
}
return $revStr;
}?> code-box

Output :
radaRxedoC

If you want to reverse user input string then we use form and get input string from user and then reverse it. For this you can see the code given below:

<!DOCTYPE html>
<html>
<body>

<?php
if(isset($_POST['submit'])){
$str = $_POST['string'];
echo getRevStr($str);
}

function getRevStr($inputStr) {
$revStr = "";
$count = strlen($inputStr) - 1;
for($i = $count; $i >= 0; $i--) {
$revStr.=$inputStr[$i];
}
return $revStr;
}
?>

<form method="POST">
<input type="text" name="string" required/>
<input type="submit" name="submit" value="Submit"/>
</form>

</body>
</html> code-box

Output :
if we input CodexRadar then we get output as follows:
radaRxedoC

Summary

In this post we learn how to reverse a string in PHP. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.

Post a Comment

Previous Post Next Post