Solution: 2
Another recursive approach:
function sr($txt) {
return (strlen($txt))
? $txt[strlen($txt) - 1] . ((strlen($txt) > 1) ? sr(substr($txt, 0, strlen($txt) - 1)) : null)
: "";
}
echo sr("abc def ghi jklm"); // Output: mlkj ihg fed cba
Explanation
strlen($txt) → checks if the string has any length.
$txt[strlen($txt) – 1] → gets the last character of the string.
If the string has more than one character, it recursively calls sr() on the substring without the last character.
Otherwise, it returns null (or “” if the string is empty).
This version handles zero-length strings safely.