PHP Program to Check if a Number is an Armstrong Number

PHP

An Armstrong number is a number in which the sum of its digits raised to the power of the number of digits is equal to the number itself. In this article, we will discuss how to check if a given number is an Armstrong number using PHP.

Examples

Let's understand Armstrong numbers with some examples ?

Example 1: 9474

This is a four-digit number with digits 9, 4, 7, and 4.

9474 = 9? + 4? + 7? + 4?
     = 6561 + 256 + 2401 + 256
     = 9474

Since the sum equals the original number, 9474 is an Armstrong number.

Example 2: 153

This is a three-digit number with digits 1, 5, and 3.

153 = 1³ + 5³ + 3³
    = 1 + 125 + 27
    = 153

Since the sum equals the original number, 153 is an Armstrong number.

Solution Approach

To check if a number is an Armstrong number, we follow these steps ?

  • Count the total number of digits in the number
  • Extract each digit and raise it to the power of the digit count
  • Sum all the powered digits
  • Compare the sum with the original number

Implementation in PHP

Here's the complete PHP implementation ?

<?php
// Function to count the number of digits in a number
function countDigits($num) {
    return strlen((string)$num);
}

// Function to check if a number is an Armstrong number
function isArmstrong($num) {
    $k = countDigits($num); 
    $sum = 0; 
    $originalNum = $num;
    
    while ($num > 0) {
        $ld = $num % 10; 
        $sum += pow($ld, $k); 
        $num = (int)($num / 10); 
    }
    
    return $sum == $originalNum;
}

// Test with different numbers
$numbers = [153, 9474, 123, 371];

foreach ($numbers as $number) {
    if (isArmstrong($number)) {
        echo "$number is an Armstrong number.
"; } else { echo "$number is not an Armstrong number.
"; } } ?>
153 is an Armstrong number.
9474 is an Armstrong number.
123 is not an Armstrong number.
371 is an Armstrong number.

How It Works

The countDigits() function converts the number to a string and returns its length. The isArmstrong() function extracts each digit using the modulo operator, raises it to the power of the digit count, and accumulates the sum. Finally, it compares the sum with the original number.

Conclusion

Armstrong numbers are special numbers where the sum of digits raised to the power of digit count equals the original number. The PHP implementation uses simple mathematical operations to efficiently check this property with O(d) time complexity.

Updated on: 2026-03-15T10:42:45+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements