How can I reverse a string in PHP without using loops or built-in functions?

Solution: 1

Here’s a very short recursive function to reverse a string:


function rev($str) {
    return $str ? rev(substr($str, 1)) . $str[0] : '';
}

Note: Since this is recursive, it will fail on strings longer than about 100 characters due to PHP’s recursion limits.

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.