Number Reverse in PHP

number reverse
PHP

Number Reverse in PHP

Write a program for number reverse in php.

Here we will discuss how to do the number reverse in php without using any string functions. Reverse number in php is a most commonly asked program and also a basic program.

Eg:- Number = 96467, Reverse = 76469

Program :

<?php  
$num=96467;  
$sum=0;    
while($num > 1)  
{  
	$rem=$num%10;  
	$sum=($sum*10)+$rem;  
	$num=$num/10;  
}  
 
echo "Reverse : $sum";  

?>
  1. Define a number which you want to find the reverse to $num
  2. Declare a variable $sum=0
  3. Loop the $num until its greater than 1
  4. Get the reminder of $num by $num%10
  5. Multiply the sum with 10 and add the reminder
  6. Divide the $num by 10
  7. Print $sum as it contains the reverse number

Logic :

$num = 96467

1st loop
$sum = 0
while(96467 > 1)
{
$rem = $num%10 = 96467 % 10 = 7
$sum = ($sum * 10)+$rem = (0 * 10) + 7 = 0+7 = 7
$num = $num/10 = 96467/10= 9646
}

2nd loop
$sum = 7
while(9646 > 1)
{
$rem = $num%10 = 9646 % 10 = 6
$sum = ($sum * 10)+$rem = (7 * 10) + 6 = 70+6 = 76
$num = $num/10 = 9646/10= 964
}

3rd loop
$sum = 76
while(964 > 1)
{
$rem = $num%10 = 964 % 10 = 4
$sum = ($sum * 10)+$rem = (76 * 10) + 4 = 760+4 = 764
$num = $num/10 = 964/10= 96
}

4th loop
$sum = 764
while(96 > 1)
{
$rem = $num%10 = 96 % 10 = 6
$sum = ($sum * 10)+$rem = (764 * 10) + 6 = 7640+6 = 7646
$num = $num/10 = 96/10= 9
}

5th loop
$sum = 7646
while(9 > 1)
{
$rem = $num%10 = 9 % 10 = 9
$sum = ($sum * 10)+$rem = (7646 * 10) + 9 = 76460+9 = 76469
$num = $num/10 = 9/10= 0.9
}

Loop end as 0.9 < 1

Click here for the program factorial in php

Click here for more knowledge on Php

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top