w3resource

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?

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