Skip to content

Instantly share code, notes, and snippets.

@amochohan
Created September 24, 2014 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amochohan/61e9f1c287e83b6b52fc to your computer and use it in GitHub Desktop.
Save amochohan/61e9f1c287e83b6b52fc to your computer and use it in GitHub Desktop.
Recurrsive function to reverse a string
<?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