How to Reverse a String with PHP

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.

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.

Demo

How to Remove Duplicate Values from an array with PHP PHP Sort Associative array by Key PHP Sort Associative array by Value Sort array in numerical order with PHP Sort array in alphabetical order with PHP Sort array in descending order PHP Sort array in ascending order in PHP How to merge two or more arrays in PHP Add elements to the end of an array in PHP Add elements to the start of an array in PHP PHP Remove First Element from an Array PHP Remove Last Element from an Array Check if Key Exists in array PHP Check if Value exists in array PHP How to reverse an array in PHP PHP Print array line by line PHP Echo array values using foreach loop Count array values in PHP PHP Count How Many Times Word appears in String How to Reverse a String with PHP Check if Variable is Null in PHP Check if Variable is Empty in PHP Check if Variable is Set or Not PHP Create New Line in PHP Remove Spaces from End of a String in PHP