w3resource logo
php Programming Exercies

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.

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");
?>

Sample 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