w3resource logo


php exercises

PHP Challenges: Reverse the digits of an integer

PHP Challenges - 1: Exercise-13 with Solution

Write a PHP program to reverse the digits of an integer.

Input : 234
Input : -234
Output : 432
Output : -432

Explanation :

PHP: Reverse the digits of an integer

Sample Solution :-

PHP Code :

<?php
function reverse_integer($n)
{
    $reverse = 0;
    while ($n > 0)
      {
        $reverse = $reverse * 10;
        $reverse = $reverse + $n % 10;
        $n = (int)($n/10);
      }
     return $reverse;
}   
print_r(reverse_integer(1234)."\n");
print_r(reverse_integer(23)."\n");
?>

Output :

4321                                                        
32

Flowchart:

PHP Flowchart: Reverse the digits of an integer

PHP Code Editor:

<?php
function reverse_integer($n)
{
    $reverse = 0;
    while ($n > 0)
      {
        $reverse = $reverse * 10;
        $reverse = $reverse + $n % 10;
        $n = (int)($n/10);
      }
     return $reverse;
}   
print_r(reverse_integer(1234)."\n");
print_r(reverse_integer(23)."\n");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.