How to reverse a string with PHP

Reversing a string in most languages is a pretty trivial task. In PHP we have a
dedicated strrev function to do so:

$string  = 'This is my awesome string!'
$reverse = strrev($string

But what if this function didn’t exist? How would you go about reversing the
string? For me, I’d loop through the string from back to forward build out a
new string. You can event accomplish this a couple of different ways!

For loop with substring

$string  = 'This is how you reverse with a for loop.'
$reverse = ''
$length  = strlen($string) - 1

for ($i = $length $i >= 0 $i--) {
    $reverse .= substr($string, $i, 1
}

String to array

$string  = 'This is how you reverse with a for loop.'
$string  = str_split($string

krsort($string

$reverse = implode('', $string

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.