Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP strrev() function

Reference for PHP strrev(): reverse the bytes of a string, why it breaks UTF-8 text, palindrome checks and a safe multibyte alternative using mb_str_split().

strrev() returns a string with its bytes in reverse order. It is a quick tool for palindrome checks, reversing identifiers and small puzzles.

The function works on bytes, not characters. For plain ASCII that is the same thing, but a UTF-8 character that uses several bytes is torn apart, producing invalid output.

PHP
<?php
echo strrev("PHP");  // PHP
echo strrev("abc");  // cba

Try it

PHP Reversing and palindromes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Multibyte text needs a different approach

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
strrev(string $string): string
Name Description
$string The string to reverse.

Return value: the reversed string.

Usage notes

  • Byte-based. Multibyte characters (UTF-8 accents, emoji, CJK) come out corrupted. Reverse an array of characters from mb_str_split() instead, as in the second example.
  • Even that is not perfect: combining marks and emoji sequences are made of several code points, and reversing them separately changes their meaning.
  • Reverse words, not letters: use explode(), array_reverse() and implode().
  • Arrays are reversed with array_reverse(); strrev() only accepts strings, and numbers are converted to strings when strict types are off.
  • Palindrome checks: normalize case and strip punctuation first, as shown above.
  • Performance: it is a single linear pass over the string, fine for very large inputs.