Write a script to reverse a string in PHP without using strrev() method. In PHP, we can reverse a string easily using strrev() method. But think how will you reverse a string without using an inbuilt strrev() method.
Reverse a String in PHP
In PHP, Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets.
For example – Let’s take a string.
1 2 3 4 5 6 7 |
//String $str = "webrewrite"; echo $str[0]; //Output - w echo $str[1]; //Output - e |
Now, it’s time to write our own custom method to reverse a string in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/** * Reverse an input string * @param String $str * @return type */ function reverseString($str) { //Initialize two indexes $start = 0; $end = strlen($str)-1; //If $start is less than $end while ($start < $end) { //Swap the position of characters $temp = $str[$start]; $str[$start] = $str[$end]; $str[$end] = $temp; $start++; $end--; } return $str; } //Output - etirwerbew echo reverseString("webrewrite"); echo "\n"; //Output - gnimmargorP PHP echo reverseString("PHP Programming"); |
In reverseString() method, we took two indexes start and end. The start index is initialized with zero and end index is initialized with string length minus one. Next, we use a while loop to check if the value of start index is less than the value of end index. After that, the characters in a string is swapped.
We can write above logic in more compact form.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * * @param type $str * @return type */ function reverseString($str) { for($i = strlen($str)-1, $j=0; $j < $i; $i--, $j++) { list($str[$j], $str[$i]) = array($str[$i], $str[$j]); } return $str; } |
In PHP, list() is used to assign a list of variables in one operation.In the above reverseString() method, we are simply swapping character and assign it using list() construct.
We can optimized our above code to traverse a string till halfway.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * * @param type $str * @return type */ function reverseString($str) { $len = strlen($str); //Traverse from 0 to len/2 for($i = 0; $i < $len/2; $i++) { $temp = $str[$i]; $str[$i] = $str[$len-$i-1]; $str[$len-$i-1] = $temp; } return $str; } //Output - etirwerbew echo reverseString("webrewrite"); echo "\n"; //Output - gnimmargorP PHP echo reverseString("PHP Programming"); |
Conclusion
I have explained how to reverse a string in PHP without using strrev() method. If you know better you to reverse a string, you can let us know through your comments.