w3resource

PHP function Exercises: Reverse a string


3. String Reversal

Write a PHP function to reverse a string.

Visual Presentation:

PHP function Exercises: Reverse a string

Sample Salution:

PHP Code:

<?php
// Function to reverse a string recursively
function reverse_string($str1)
{
    // Get the length of the string
    $n = strlen($str1);
    
    // Base case: if the string has only one character, return the string itself
    if ($n == 1)
    {
        return $str1;
    }
    else
    {
        // Decrement the length of the string
        $n--;
        
        // Recursively reverse the substring starting from the second character
        // and concatenate the first character to it
        return reverse_string(substr($str1, 1, $n)) . substr($str1, 0, 1);
    }
}

// Call the reverse_string function with the argument '1234' and print the result
print_r(reverse_string('1234') . "\n");
?>

Output:

4321

Explanation:

In the exercise above,

  • The function "reverse_string()" takes a single parameter '$str1', representing the input string to be reversed.
  • It calculates the length of the input string using 'strlen($str1)' and stores it in the variable '$n'.
  • If the length of the string is 1, it means the string is already reversed, so it returns the string itself.
  • Otherwise, it decrements the length of the string by 1 ($n--), and then recursively reverses the substring starting from the second character using 'substr($str1, 1, $n)', and concatenates the first character using 'substr($str1, 0, 1)'.
  • This recursive process continues until the base case (string length equals 1) is reached, and the reversed string is gradually built up.
  • Finally, the function is called with the argument '1234', and the reversed string is printed using "print_r()" function.

Flowchart :

Flowchart: Reverse a string

For more Practice: Solve these Related Problems:

  • Write a PHP function to reverse a string by converting it to an array of characters and then using array_reverse().
  • Write a PHP script to reverse a string using recursion and output the reversed string along with the recursion depth.
  • Write a PHP function to reverse only the letters of a string, keeping non-letter characters in their original positions.
  • Write a PHP program to reverse a Unicode string, ensuring proper handling of multibyte characters using mbstring functions.

Go to:


PREV : Prime Number Checker.
NEXT : Array Sorting.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.