Reversing a String in PHP

The other day I was asked to write out the basic algorithm for reversing a string. I could do it in whatever language I wanted; I chose PHP. I knew that in Ruby you can just do strvar.reverse, but I didn’t quite remember if PHP had a simple single function to accomplish this. It does, but there are many different combinations too.
PHP has a built in function to reverse strings. It is strrev($string). A common use is:
//PHP Manual: string strrev ( string $string )
$str = "judicious";
echo strrev($str); // suoiciduj//.0000159740447998 sec. – First Run -> 1.6E-5
//.0000150203704834 sec. – Second Run
So simple, yet I didn’t remember that because I never use it. However, I think it was better at the time for me to show that I could come up with an algorithm to yield the above result. I have just completed running "time trial" tests on about 5 different ways of reversing a string. I ran each algorithm in its own page and timed them using the microtime(true) function which was used to return microsecond calculations. I wanted to see which was the best way without knowing about strrev().
The substr() reverse algorithm:
//Vars
$str = "judicious";
$output = "";$startTime = microtime(true);
for($i=(strlen($str)-1);$i>=0;$i–)
$output .= substr($str, $i, 1);
$ttlTime = microtime(true) – $startTime;
echo "String: $str<br/>";
echo "Completed in [$ttlTime sec.]<br/>";
echo "Result: $output";//.0000751018524170 sec. – First Run -> 7.5E-5
//.0000472068786621 sec. – Second Run
This was the algorithm that I answered the question with. I decided to use substr() to cut the $str variable down to the 1 single last character in $i th position starting at the end and working backwards. I thought it was good, but check it in comparison with strrev().
The exact character reverse algorithm:
for($i=(strlen($str)-1);$i>=0;$i–)
$output .= $str{$i};//.0000689029693604 sec. – First Run -> 6.9E-5
//.0000450611114502 sec. – Second Run
I am convinced that some version of this algorithm runs in the back of strrev(). When running right after strrev() in the same script it goes much faster. Calling each individual character in string $str by using the curly brackets.
The str_split() one liner reverse algorithm:
$output = implode(array_reverse(str_split($str,1)));
//.0000629425048828 sec. – First Run -> 6.3E-5
//.0000419616699219 sec. – Second Run
I had a similar algorithm using a for loop again, but this runs way lighter. I like the readability of this algorithm too. First it splits the string into an array of pieces 1 in length. Next it reverses the array and then implodes the array back into a string.
Let’s review the time score card!
| Algorithm: | 1st Run: (s) | 2nd Run: (s) |
| strrev() | 1.6E-5 | 1.5E-5 |
| substr() | 7.5E-5 | 4.5E-5 |
| Exact char | 6.8E-5 | 4.5E-5 |
| str_split() | 6.3E-5 | 4.2E-5 |
This goes to show you that there are many ways of doing the same thing and sometimes people have already done them. PHP has many awesome built-in functions that I wish languages like C++ without having to import some library. Check out the PHP Manual online. I visit it often when I am developing.
UPDATE: Interestingly as I was making my calcuations I noticed that when I used a custom function that exploded microtime() (I guess before PHP5 with the "true" param) it added about 1.1E-4 seconds onto the execution timer. Therefore, use microtime(true) if you have PHP5.
Anytime you use the built in functions for a higher level language like PHP they will be much faster than using functions within the language to approximate that same built in routine…as you have demonstrated by showing a 4 fold speedup using strrev() instead of exploding reversing and imploding. Because PHP is based on C (http://en.wikipedia.org/wiki/PHP) using built in functionality is way faster.
But…. as you have demonstrated if you cant use the built in function sometimes constructing your own is possible, fun and – if not too slow – useful!
Hmm…with this kind of analysis I’m afraid that you’re starting sound like a Numerical Analyst…perhaps you will soon drift to the dark side and become and Applied Mathematician.
Reply
Theo, I knew there had to be some built in function in PHP because of the plethora of other readily available functions in the language.
I totally forgot that you could access a single character in a string by using $str{4}. Quite neat. C++ uses str.at(4) which won’t allow you to go out of the dimension.
When I run all of the algorithms in one script, PHP looks like it nicely uses caching of the method and speeds up the process ever so slightly.
Reply