How to reverse a string with PHP

Josh Sherman
1 min read
Software Development 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);


$reverse = implode('', $string);

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles