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”;
- strrev()
$string = strrev($string);
This is almost cheating because PHP has a built in function… but this is the easiest way for sure - Array Reverse
$string = implode('',array_reverse(str_split($string))); - 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”;
- String Split Reverse Join
string = string.split('').reverse().join(''); - For Loop
var newString = []; for (i=(string.length)-1; i>=0; i--) { newString.push(string[i]); } string=newString.join('');