Created
September 24, 2014 11:35
-
-
Save amochohan/61e9f1c287e83b6b52fc to your computer and use it in GitHub Desktop.
Recurrsive function to reverse a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function reverseString($string){ | |
//Is this method being recurrsively called, i.e. do we still have part of the string being passed to the function to be reversed? | |
if(strlen($string)>1){ | |
/* | |
* Return the last letter of the string, and append via calling this method again recursively (passing the remainder of the un-reversed string) | |
* to continue reversing the remainder of the string | |
*/ | |
return $string[strlen($string)-1] . reverseString( substr( $string, 0, strlen($string)-1 ) ); | |
} | |
else{ | |
//The reveresed string | |
return $string[strlen($string)-1]; | |
} | |
} | |
$string = "Hello, nice to meet you!"; | |
echo $string . "<hr/>"; | |
echo reverseString($string); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment