w3resource
php Programming Exercies

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:

<?php
function reverse_string($str1)
{
 $n = strlen($str1);
 if($n == 1)
   {
    return $str1;
   }
 else
   {
   $n--;
   return reverse_string(substr($str1,1, $n)) . substr($str1, 0, 1);
   }
}
print_r(reverse_string('1234')."\n");
?>

Sample Output:

4321

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?



New Content: Composer: Dependency manager for PHP, R Programming