How to Reverse a String in PHP without using strrev function

This is Very simple to Reverse a String in PHP by using inbuild function strrev. But sometimes in php interview you may come across the task to Reverse a String in PHP without using strrev function.

You can answer this question with few steps:

  • Assign the given string to the variable
  • Calculate the length of the string
  • Declare a variable in which you have to store the reversed string
  • Iterate the string using for loop with appropriate looping and count
  • Concatenate the string inside the for loop
  • Display the reversed string.

The below php function to reverse a sting without Array and strrev (inbuilt) function.

Source Code:

<?php 

function myStrRev($string){
$string_length = strlen($string); // finding string length
$reversed_string = ''; // store the reversed string

for($i=$string_length;$i>-1;$i--){ // iterating to reverse the string
$reversed_string .= $string{$i};
}
return $reversed_string;
}

How to use this function

Output / Usage:

<?php 
$string = "Hello Eduzip";

echo myStrRev($string); “// output will be 'pizudE olleH'”;

Comments: (Your feedback is valuable to us)