An Armstrong number equals the sum of its digits raised to the number of digits. Use integer division when removing the right-most digit so the loop always works with integers.
<?php
$number = 153;
$original = $number;
$power = strlen((string) $number);
$sum = 0;
while ($number > 0) {
$digit = $number % 10;
$sum += $digit ** $power;
$number = intdiv($number, 10);
}
echo $sum === $original ? 'Armstrong number' : 'Not an Armstrong number';
?>
$n1=153;
$n2=$n1;
$sum=0;
while($n1>0){
$d=$n1%10; // reminder of the division
$sum=$sum + pow($d,3);
//$n1=floor($n1/10);
$n1=intdiv($n1, 10);
//$n1=intdiv($n1,10); // for PHP 7 and above
}
if($sum==$n2){
echo "$n2 is an Armstrong number ";
}else{
echo "$n2 is NOT an Armstrong number ";
}
Output
153 is an Armstrong number
for($i=10;$i<=100000;$i++){
$n2=$n1=$i;
$p=strlen($n1); // Number of digits in the number
$sum=0;
while($n1>0){
$d=$n1%10; // reminder of the division
$sum=$sum + pow($d,$p);
//$n1=floor($n1/10);
$n1=intdiv($n1, 10);
//$n1=intdiv($n1,10); // for PHP 7 and above
}
if($sum==$n2){
echo "$n2 is an Armstrong number <br>";
}
}
Output is here
153 is an Armstrong number
370 is an Armstrong number
371 is an Armstrong number
407 is an Armstrong number
1634 is an Armstrong number
8208 is an Armstrong number
9474 is an Armstrong number
54748 is an Armstrong number
92727 is an Armstrong number
93084 is an Armstrong number
Introduction to PHP Factorial of a number Sum of Digits of a number Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.