How to Reverse a String in PHP without using strrev() Method – Programming Code Examples
PHP

How to Reverse a String in PHP without using strrev() Method2 min read

Write a script to reverse a string in PHP without using strrev() method. In PHP, we can reverse a string easily using strrev() method. But think how will you reverse a string without using an inbuilt strrev() method.

Reverse a String in PHP

In PHP, Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets.




For example – Let’s take a string.

Now, it’s time to write our own custom method to reverse a string in PHP.

In reverseString() method, we took two indexes start and end. The start index is initialized with zero and end index is initialized with string length minus one. Next, we use a while loop to check if the value of start index is less than the value of end index. After that, the characters in a string is swapped.

We can write above logic in more compact form.

In PHP, list() is used to assign a list of variables in one operation.In the above reverseString() method, we are simply swapping character and assign it using list() construct.

We can optimized our above code to traverse a string till halfway.

Conclusion

I have explained how to reverse a string in PHP without using strrev() method. If you know better you to reverse a string, you can let us know through your comments.

Leave a Comment