How to reverse a string in PHP?

How to reverse a string in PHP?

Reversing a string is a very common Question in the Interviews and is a tricky one. Ideally, you will be asked to write an algorithm to reverse a string with some constraints like algorithm should be having a linear complexity or Should be order of Big Oh O(n) or algorithm must use recursion and all.

So, in this post we will see reversing a string in PHP using recursion and iteration.

Reverse a String using recursion

In this implementation we remove the head character upon each call. When string reached to single character that’s a base case for terminating the recursion and the remaining string is returned.

Reverse a String using a loop

In this implementation we simply iterate the string from bottom to top or right to left, pick the character and put it into another string. Although, It’s not the best practice but lets see how it works.

= 0;  $reversedString .= $string[$i--]) {}
    return $reversedString;

echo reverseStringIterative("Codezuzu") ."\n";
echo reverseStringIterative("Hello World") ."\n";
echo reverseStringIterative("IT") ."\n";
echo reverseStringIterative("A") ."\n";

// Output
dlroW olleH


Reverse a String using a Recursion with Divide and Conquer

This is again the implementation using recursion but it takes advantage of the divide and conquer algorithm. So in each call, we find the mid-point of the string and then flip the left and right substring.

So thats about the reversing a string in PHP. We may use PHP’s inbuilt function strrev as well to achieve this.
Let me know your thoughts in the comments below. Happy Coding !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.