You can reverse a string in PHP simply by using the built-in strrev() function. For more advanced needs (e.g., UTF-8 support or recursion), you can also reverse it via loops, array methods, or multibyte functions.
Reversing strings in PHP is useful for palindrome checks, data obfuscation, and text manipulation. However, handling multibyte (UTF-8) text needs care to avoid broken characters. In this guide, you’ll explore methods, trade-offs, and ready-to-use code examples.
Quick Summary of Reverse String in PHP
Method | Use Case | Strength | Limitation |
---|---|---|---|
strrev() | ASCII strings | Fast & simple | Doesn’t work reliably with UTF-8 |
Loop / index swap | Custom logic, in-place | Full control | More code, slower for large strings |
Array reverse method | When you want array ops | Clear logic | More memory overhead |
Multibyte (mb) method | Unicode / UTF-8 strings | Correct for multibyte | Slightly slower, requires mb functions |
What Does strrev()
Do?
The simplest way to reverse a string in PHP is by using the built-in strrev()
function. It takes a string as input and returns the reversed version.
Syntax
<?php echo strrev("Newtum"); // Output: mutweN ?>
Behavior
- Works perfectly for ASCII characters.
- Ideal for quick and small tasks such as palindrome checking or string manipulation.
However, there’s a catch—strrev()
doesn’t handle multibyte (UTF-8) characters correctly. For example:
<?php echo strrev("नमस्ते"); // Output: Broken characters ?>
This happens because strrev()
reverses bytes, not full multibyte characters—leading to corrupted output for non-ASCII text.

Reversing Using Loops / Manual Swap
When you need complete control, you can reverse a string manually using loops. This method is educational and helps understand string indexing in PHP.
Example: Using a Backward Loop
<?php $string = "Newtum"; $reversed = ""; for ($i = strlen($string) - 1; $i >= 0; $i--) { $reversed .= $string[$i]; } echo $reversed; // Output: mutweN ?>
Two-Pointer Swap Method
This in-place approach uses two pointers (start and end) to swap characters:
<?php function reverseString($str) { $chars = str_split($str); $left = 0; $right = count($chars) - 1; while ($left < $right) { [$chars[$left], $chars[$right]] = [$chars[$right], $chars[$left]]; $left++; $right--; } return implode('', $chars); } echo reverseString("Newtum"); // Output: mutweN ?>
Reversing Using str_split()
, array_reverse()
& implode()
A more readable approach involves converting a string into an array of characters, reversing it, and joining it back.
Step-by-Step Example
<?php $string = "Newtum"; $reversed = implode('', array_reverse(str_split($string))); echo $reversed; // Output: mutweN ?>
When This Is Useful
- When applying filters or transformations to characters before reversing.
- Great for combining with array-based operations (e.g.,
array_map()
for case conversion).
Handling Multibyte / UTF-8 Strings
For Unicode strings, ASCII-based reversal methods fail because characters are stored using multiple bytes. Naive methods may split or reorder bytes incorrectly.
Correct Way to Reverse UTF-8 Strings
Use mb_strlen()
, mb_substr()
, or preg_split('//u', …)
for multibyte safety.
<?php function mb_strrev($str) { $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY); return implode('', array_reverse($chars)); } echo mb_strrev("नमस्ते"); // Output: ेत्समन ?>
This ensures each Unicode character is treated as a single unit—perfect for international text.
Recursion Method (Educational)
Recursion isn’t the most efficient, but it demonstrates a logical and mathematical approach to string reversal.
Example
<?php function reverseRecursive($str) { if (strlen($str) <= 1) { return $str; } return reverseRecursive(substr($str, 1)) . $str[0]; } echo reverseRecursive("Newtum"); // Output: mutweN ?>
Pros and Cons
Pros | Cons |
---|---|
Elegant and conceptually simple | Inefficient for long strings |
Great for learning recursion | Can hit recursion depth limits |
Real-World Applications of String Reversal in PHP
- Social Media Algorithms: Social media companies, like Facebook, often use basic string manipulations in their algorithms. A reverse string can be handy for their data analysis purposes, such as reversing a user’s name for encryption purposes or for fun display effects in the app.
Using this technique, they can ensure that data is securely encrypted for parts of their application$originalString = "JohnDoe";
echo strrev($originalString); // Output: eoDnhoJ - Backend Data Processing: Companies like Google might use reverse string functions as part of their data processing pipelines. It ensures data integrity and helps detect patterns by reversing strings in compiled data logs.
This application assists in quickly identifying and dealing with repeated error messages$log = "Error404";
echo strrev($log); // Output: 404rorre - Palindromes and Word Games: A company like Hasbro could utilize string reversal for developing word games, checking if words form palindromes for bonus points or special rewards.
Such implementations enrich game dynamics, offering diverse player challenges.$word = "racecar";
if ($word == strrev($word)) {
echo "It's a palindrome!"; // Output: It's a palindrome!
}
Interview Questions: Reverse String
Understanding how to reverse a string in PHP isn’t just about being a coding whiz—it’s about problem-solving and thinking in new ways. Here’s a fun list of fresh questions people are asking on forums and other platforms about reversing strings in PHP. Let’s dive in!
- How do you reverse a string recursively in PHP?
Breaking a problem down into smaller parts is key. For reversing a string recursively, we slice our way through it, taking the last character and appending it to the reversed version of the substring. Here’s the code:function reverseStringRecursively($str) { if (strlen($str) == 0) { return ""; } else { return reverseStringRecursively(substr($str, 1)) . $str[0]; } }
- Can you reverse a string using array functions?
Absolutely! This can be handy as array functions are quite powerful. You can split the string into an array, reverse it, and then smash it back into a string:function reverseStringWithArray($str) { return implode('', array_reverse(str_split($str))); }
- Is there a way to reverse a string without using built-in PHP functions?
Yes, indeed! Implementing your own logic could offer insights. Here’s a simple loop solution:function reverseStringManually($str) { $reversed = ""; $len = strlen($str); for ($i = $len - 1; $i >= 0; $i--) { $reversed .= $str[$i]; } return $reversed; }
- How do you handle multibyte characters in a string reversal?
Handling multibyte characters requires a bit more finesse. Use the `mb_strlen` and `mb_substr` functions for a foolproof approach:function reverseMultibyteString($str) { $reversed = ''; $length = mb_strlen($str, 'UTF-8'); while ($length > 0) { $reversed .= mb_substr($str, --$length, 1, 'UTF-8'); } return $reversed; }
- Can reversing a string be made memory-efficient?
By processing directly on the string and reducing extra variable usage, you can optimize memory usage. Yet, this requires a careful balance between readability and efficiency. - Is there a unique algorithm inspired by other languages to reverse a string?
Certainly! For example, implementing the two-pointer approach, popular in languages like Python, can work just as well in PHP. - What are common mistakes to avoid while reversing strings in PHP?
Look out for off-by-one errors. Always remember strings are zero-indexed. Additionally, managing multibyte characters without the right functions will also lead to trouble. - How can you measure the time complexity of a string reversal function?
You can use PHP’s `microtime()` function to compare execution time between different reversal strategies for insights on performance. - Do you need special considerations for reversing numeric strings?
Yes! Although numbers are stored as strings, always ensure the reversed result is considered from a string perspective to avoid unexpected type juggling. - How do encoding and internationalisation (i18n) affect string reversal?
When dealing with different languages and encodings, primarily with UTF-8, string reversal should account for bytes and not just simple character swaps to avoid data corruption.
These questions not only help you get a better grip on string reversal but also strengthen your fundamental coding skills, giving you the confidence to face any problem head-on. Happy coding!
Our AI-powered php online compiler offers a seamless coding experience. Instantly write, run, and test your ‘php’ code with the help of AI. It’s designed to streamline your coding process, making it quicker and more efficient. Try it out, and see the difference AI can make!
Conclusion
Reverse String in PHP is a simple yet effective exercise that builds your foundational programming skills, boosts confidence, and enhances problem-solving abilities. Why not give it a shot today? For a deeper dive into programming, explore Newtum to learn more about languages like Java, Python, and C++.
Edited and Compiled by
This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.