How to Use strrev() Function in PHP 8.4 and PHP 8.5?

The strrev() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes, deprecations, or behavioral modifications for this function in either release. The official migration guides and release notes for PHP 8.4 and 8.5 do not mention any changes to strrev().

Function

strrev() reverses a string and returns the result.

Signature:

strrev(string $string): string

Key Behavior:

Byte Based Reversal: strrev() operates on bytes, not characters. It is safe for single-byte encodings (like ASCII or ISO-8859-1) but will produce garbled output ("gibberish") for multibyte encodings such as UTF-8 if the string contains non-ASCII characters.

Examples

1. Basic Usage (ASCII)

<?php
echo strrev("Hello world!");
// Outputs: !dlrow olleH
?>

This is the standard example provided in the PHP manual .

2. The Multibyte Limitation (UTF-8)

<?php
// This will likely produce broken/garbled characters
echo strrev("☆❤world");
// Outputs something like: dlrow��☆ (incorrect)
?>

Because strrev() reverses bytes, a multi-byte UTF-8 character like "☆" gets split apart, corrupting the string.

Multibyte Strings

If you need to reverse a UTF-8 string (containing emojis, accented characters, or non-Latin scripts), do not use strrev(). Instead, you should use a multibyte-safe approach. The PHP manual user notes suggest using mb_str_split() combined with array_reverse():

<?php
function mb_strrev(string $string, ?string $encoding = null): string {
   $chars = mb_str_split($string, 1, $encoding ?? mb_internal_encoding());
   return implode( , array_reverse($chars));
}

echo mb_strrev("☆❤world");
// Outputs: dlrow❤☆
?>

This method correctly handles UTF-8 characters by treating them as individual units rather than raw bytes.

 

5 Views