In this tutorial we will learn How to Reverse a String with PHP. We can reverse the string using PHP strrev() Function and we can also reverse any string using simple for loop without strrev() which is a built-in function made for this purpose.
Table of Contents
PHP strrev() Function
PHP strrev() Function is a built-in function which reverses the string assigned to it.
strrev() function takes only one parameter which is the string that we want to reverse.
<?php
$string ='HowToCodeSchool.com';
$reversedString = strrev($string);
echo $reversedString;
?>
In above code the original string 'HowToCodeSchool.com' will be converted to 'moc.loohcSedoCoTwoH'.
Using For Loop
We can reverse the string using simple for loop. Take a look at the code given below.
<?php
$string ='HowToCodeSchool.com';
$length = strlen($string);
for ($i=$length; $i >= 0 ; $i--)
{
echo $string[$i];
}
?>
In above code, we have used strlen() function to calculate the length of string and for loop is then used to get and print each character of string from last to first.