PHP function Exercises: Reverse a string
Write a PHP function to reverse a string.
Visual Presentation:

Sample Salution:
PHP Code:
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 :

PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a function to check a number is prime or not.
Next: Write a function to sort an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.