PHP function Exercises: Reverse a string

PHP function: Exercise-3 with Solution

Write a function to reverse a string.

Pictorial Presentation:

PHP function Exercises: Reverse a string

Sample Salution:

PHP Code:

function reverse_string($str1)
 $n = strlen($str1);
 if($n == 1)
    return $str1;
   return reverse_string(substr($str1,1, $n)) . substr($str1, 0, 1);

Sample Output:


Flowchart :

Flowchart: Reverse a string

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.

Share this Tutorial / Exercise on : Facebook and Twitter

PHP: Tips of the Day

Formatting a number with leading zeros in PHP

Use sprintf :

sprintf('%08d', 1234567);

Alternatively you can also use str_pad:

str_pad($value, 8, '0', STR_PAD_LEFT);

Ref : https://bit.ly/3fS2OLd