0
0
PhpHow-ToBeginner · 3 min read

How to Reverse a String in PHP: Simple Syntax and Examples

In PHP, you can reverse a string easily using the strrev() function. Just pass your string as an argument to strrev(), and it returns the reversed string.
📐

Syntax

The strrev() function takes one parameter, which is the string you want to reverse. It returns a new string with the characters in reverse order.

  • Parameter: The input string to reverse.
  • Return: The reversed string.
php
strrev(string $string): string
💻

Example

This example shows how to reverse the string "hello" using strrev(). The output will be the reversed string "olleh".

php
<?php
$original = "hello";
$reversed = strrev($original);
echo $reversed;
?>
Output
olleh
⚠️

Common Pitfalls

One common mistake is trying to reverse a string by looping through characters manually, which is unnecessary and error-prone. Another is forgetting that strrev() works only on strings, so passing other types may cause unexpected results.

Also, strrev() does not handle multibyte (Unicode) characters correctly, so for strings with special characters like emojis or accented letters, it may produce wrong output.

php
<?php
// Wrong way: manual loop (complex and unnecessary)
$input = "hello";
$output = '';
for ($i = strlen($input) - 1; $i >= 0; $i--) {
    $output .= $input[$i];
}
echo $output; // works but more code

// Right way: use strrev()
echo strrev($input); // simpler and clearer

// Note: For multibyte strings, use mbstring extension functions instead
?>
Output
olleholleh
📊

Quick Reference

Remember these tips when reversing strings in PHP:

  • Use strrev() for simple ASCII strings.
  • For multibyte strings (like UTF-8), consider using mb_str_split() and array_reverse() combined.
  • Always pass a string to strrev() to avoid unexpected results.

Key Takeaways

Use PHP's built-in strrev() function to reverse strings simply and efficiently.
strrev() works well for ASCII strings but not for multibyte Unicode characters.
Avoid manual loops to reverse strings; strrev() is clearer and less error-prone.
For multibyte strings, use mbstring functions combined with array operations.
Always ensure the input to strrev() is a string to prevent unexpected behavior.