How to reverse a string in PHP without strrev(inbuilt) and Array function

Reverse a string in PHP is pretty simple.  PHP provides inbuilt function to reverse a string PHP: strrev – Manual but knowing the logic of how it works is very simple and interesting. In the interview you may come across “Write a PHP function which should reverse the given string, condition u should not use strrev (inbuilt) function and array functions “.  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 code snippets shows the PHP code to reverse a sting without Array and strrev(inbuilt) function.

 

3 Responses to “How to reverse a string in PHP without strrev(inbuilt) and Array function”
  1. iqbal rana says:

    -1;$i–)
    {
    echo substr($text,$i,1);

    }

    ?>

  2. Mayank says:

    = 0; $i–){

    $rstr .= $str[$i];

    }

    echo $rstr;

    ?>

Leave a Reply