Nathan Firth

  • Archive
  • RSS

Some different ways of reversing a string in PHP & JavaScript

I was looking at some of the different ways of reversing a string in PHP and in JavaScript. There are so many ways of accomplishing such a simple task but I wanted to compare some of the different ways.

PHP

$string = “This is a test”;

  1. strrev()
    $string = strrev($string);
    This is almost cheating because PHP has a built in function… but this is the easiest way for sure
  2. Array Reverse
    $string = implode('',array_reverse(str_split($string)));
  3. For Loop
    $string = str_split($string);
    for ($i=count($string)-1; $i>=0; $i--) {
        $newstring .= $string[$i];
    }
    $string = $newstring;
    

JavaScript

var string = “This is a test”;

  1. String Split Reverse Join
    string = string.split('').reverse().join('');
  2. For Loop
    var newString = [];
    for (i=(string.length)-1; i>=0; i--) {
        newString.push(string[i]);
    }
    string=newString.join('');
    
  • 3 months ago
  • Permalink
  • Share
    Tweet
← Previous • Next →

About

I'm an internet entrepreneur, web developer, designer, lover of Jesus from San Diego. Originally from Sweden. I have a beautiful wife, and two amazing kids.
Follow @nathanfirth

loading tweets…

  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco but customized by Nathan Firth.

Powered by Tumblr