PHP has a predefined function to reverse a string but we can do this task in with two methods. In interviews there could be a condition that reverse a string in PHP without using strrev() function.
In this tutorial we will learn both ways to reverse a string.
1. Reverse string in PHP with strrev() function -
<?php
$str = "Thetutorialsway";
echo "Reversed string is".strrev($str);
?>
echo "Reversed string is".strrev($str);
?>
2. Reverse string in PHP without strrev() function -
- Assign the string to a variable
- Calculate length of the string and assign to a variable
- Declare variable to hold the reverse string
- Run for loop
- Concatenate string inside for loop
<?php
$str = "Thetutorialsway";
$len = strlen($str);
$revstr = "";
for($i = ($len-1);$i>=0;$i--)
{
$revstr .= $str[$i];
}
echo "The reverse string is " . $revstr;
?>
$str = "Thetutorialsway";
$len = strlen($str);
$revstr = "";
for($i = ($len-1);$i>=0;$i--)
{
$revstr .= $str[$i];
}
echo "The reverse string is " . $revstr;
?>
We shared this tutorial for you to learn both ways to reverse string in PHP. Hope you have understood the concept.
If this tutorials helpful, Please share this with your friends and like our Facebook page.

0 Comments