strrev
strrev($string)
Returns the string backwards – the last character becomes the first. It works with bytes, so it is reliable only for text without accents. UTF-8 text has to be reversed by characters.
Parameters
- $string – the text to reverse.
Examples
echo strrev("garth"); // htrag
echo strrev("12345"); // 54321
// a palindrome – a word that reads the same from both sides
$word = "kayak";
var_dump($word === strrev($word)); // bool(true)
// processing a number from the right – groups of three digits
echo strrev(implode(" ", str_split(strrev("1234567"), 3))); // 1 234 567
// strrev breaks UTF-8 text – it reverses bytes, not characters
var_dump(mb_check_encoding(strrev("café"), "UTF-8")); // bool(false)
// reversing by characters (mb_str_split exists since PHP 7.4)
echo implode("", array_reverse(mb_str_split("café"))); // éfac
// the same in older PHP versions
echo implode("", array_reverse(preg_split('//u', "crème", -1, PREG_SPLIT_NO_EMPTY))); // emèrc
Things to watch out for
- An accented letter takes two bytes in UTF-8 and strrev swaps them. The result is invalid text, displayed as question marks or unreadable characters. Reverse text with accents by characters as in the example.
- The function is only for strings. array_reverse() reverses the order of the elements in an array.
- Testing a whole sentence for a palindrome needs the text normalized first – converted to lowercase, with spaces and punctuation removed.
- Formatting a number by thousands in the example only shows how to work from the right, the ready-made solution is number_format().
Related functions:
str_split()
strlen()
number_format()