Reversing a String in PHP
Since recently setting up a forum for Three Devs and a Maybe, we have started to partake in a weekly code-kata. What could be more fitting to start with than the common interview question, reversing a string in ‘X’ language. In this case the language is PHP, and below are some of the many ways contrived to solve the problem.
The implementation below is the most simple, taking advantage of PHP’s vast amount of ‘built-in’ functions to reverse the supplied string.
In a similar manner, we are able to compose a ‘reverse’ function by joining (alias for ‘implode’) a reversed array of the string characters.
The most imperative approach to reverse a string is by looping over each character with indexes at each end, swapping their contents upon each iteration. PHP’s ability to access individual characters in an array manner turns out to be very useful in this case.
Though not best practice, the desired result can be compacted into a single ‘for’ loop declaration, shown below.
Another non-practical approach using the ‘array_walk’ function can be found below. An interesting implementation detail, is how you are able to clearly see that a copy of ‘$out’ is being passed into the closure function.
The second group of implementations contrived used forms of recursion to achieve the desired result. The first of such methods is a simple recursive invocation of the function, removing the head character upon each call. Once the string has reached one character, the base-case has been hit and the remaining string is simply returned.
The implementation below takes advantage of the divide and conquer algorithm paradigm, flipping the left and right substrings upon each recursive invocation. Similar to the previous example, if the base-case of a single character string is met, the remaining string is simply returned.
PHP’s in-built support for Unicode strings is ‘somewhat’ lacking, as such, extra steps are required to correctly reverse a string of this type. As Unicode character representations can consist of multiple bytes (i.e. UTF-8), we are unable to naively use ‘strlen’ and ‘str_split’ (which assume a character is always a single byte). The implementation below uses ‘preg_split’ support for Unicode characters, to correctly split the string into characters for us to reverse.
Using some endianness conversion trickery we are able to use PHP’s in-built ‘strrev’ function. The implementation below uses ‘iconv’ to achieve the desired results.
Similar in-nature to the previous example, we are instead now using the ‘mb’ library to perform the conversion.