Reverse number program using php

Hi there,
I am going to show , How to reverse number  using php.
Reverse number using without php function:
Example:
Input number is: 12345
Reverse number will be: 54321


Logic:
  1. Let's Take a number12345.
  2. Assign 0 to the variable, in which we are going to store reverse number 
  3. Run the following two steps until number is not zero
  4. Get the digit using modules (%) operator and add it into the ‘reverse*10’
  5. Now, divide the number by 10
  6. Finally, when number will be zero, print the ‘reverse’
<?php
    //input
    $num = 12345;
    //reverse should be 0
    $reverse = 0;
    //run loop until num is not zero
    while ($num != 0)
    {
        $reverse = $reverse * 10 + $num % 10;
        $num = (int)($num / 10);
    }
    /printing the reverse number
    echo "Reverse number of 12345 is: $reverse";

?> 
Output: Reverse number of 12345 is: 54321

Reverse number Program in PHP:
<?php
function reverse_number($number)
{
   
   /* Typecast the number into string. */

    $snum = (string) $number;
    /* Reverse the string. */
    $revstr = strrev($snum);
    /* Typecast string into int. */
    $reverse = (int) $revstr;
    return $reverse;
}
 echo "Reverse number of 12345 is:".reverse_number(12345);

?>
Output: Reverse number of 12345 is: 54321

Happy coding!


Comments

Post a Comment