Check Armstrong Number in PHP

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digits & powers

What you’ll learn

  • The Armstrong (narcissistic) condition: sum of each digit raised to the number of digits.
  • A clear algorithm, pseudocode, and two PHP programs: one number and a range scan.
  • Why integer exponentiation is safer than pow() for exact checks, plus edge cases and complexity.
  • A browser live preview that mirrors the same digit-power rule.

Overview

An Armstrong number equals the sum of its decimal digits, each raised to the power of how many digits it has. Classic example: 153 = 1³ + 5³ + 3³. This tutorial shows how to implement that test in PHP, then scan a range.

Two programs

A single-value check (try 153) and a range listing (for example 1 to 200).

Live preview

See digit count k, the expanded sum of each dk, and the verdict without running PHP.

Interview polish

Guards for n ≤ 0, integer powers, overflow notes, and complexity in one place.

Prerequisites

Comfort with loops, integer division, and the modulo operator % is enough to follow the code.

  • PHP basics: variables, functions, if, and for/while loops.
  • Extracting the last digit with $n % 10 and shifting with intdiv($n, 10).
  • Optional: understanding that the exponent is the digit count, not the digit value.

What is an Armstrong number?

Let n be a positive integer with k decimal digits. Then n is an Armstrong number (in base 10) when the sum of each digit raised to the power k equals n.

digit1k + digit2k + ... + digitkk = n

The exponent is always the digit count. For a 3-digit number like 153, the exponent is 3 for every digit.

Armstrong sum of (each digit)k = n
Not Armstrong that sum ≠ n
Synonyms narcissistic / PPDI (base 10)

Mathematical definition

In base 10, if n has k digits, then n is Armstrong when the sum of each digit raised to k equals n.

Three-digit template

For 100 ≤ n ≤ 999, write n = 100a + 10b + c. Armstrong means a³ + b³ + c³ = 100a + 10b + c.

Examples: 153, 370, 371, 407 are the only three-digit Armstrong numbers besides the one-digit cases.

Intuition and examples

Count how many digits n has. Then peel digits off from the right, raise each digit to that count, and add. If the total equals n, it is Armstrong.

Each card shows the digit-power sum with the same exponent k everywhere.

153 Armstrong
Digits
3, so exponent 3
Sum
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Verdict
Equals nArmstrong.
123 Not Armstrong
Digits
3, exponent 3
Sum
1³ + 2³ + 3³ = 1 + 8 + 27 = 36
Verdict
36 ≠ 123 — not Armstrong.
7 Armstrong
Digits
1, exponent 1
Sum
7¹ = 7
Verdict
Every 1–9 works the same way.

Takeaway: the exponent is the length of n, not the digit itself.

Live preview

Type a positive integer n. The widget counts decimal digits k, builds the sum of each digit to the kth power, and compares it to n. Caps at 999 999 999 to keep arithmetic predictable.

  1. Try 153, 123, or a single digit.
  2. Press Run check (or Enter).
  3. Read the expanded sum line and the verdict.

Use integers n ≥ 1.

Live result
Press “Run check” to see digit powers and the verdict.

Algorithm

Goal: decide whether a given n is an Armstrong number in base 10.

Validate n

If n ≤ 0, return false.

Count digits k

Copy n to a temporary variable and repeatedly divide by 10 until it becomes 0, counting steps.

Accumulate digit powers

Walk digits again with % 10 and intdiv( , 10). Add digit^k using integer multiplication.

Compare

If the sum equals the original n, it is Armstrong.

📜 Pseudocode

Pseudocode
function digitCount(n):
    k <- 0
    t <- n
    while t > 0:
        k <- k + 1
        t <- floor(t / 10)
    return k

function isArmstrong(n):
    if n <= 0:
        return false
    k <- digitCount(n)
    sum <- 0
    t <- n
    while t > 0:
        d <- t mod 10
        sum <- sum + (d to the power k)   // integer power
        t <- floor(t / 10)
    return sum = n
1

Check a single number (program with explanation)

Uses a small ipow helper so every step stays in integer arithmetic — no floating-point rounding.

php
<?php
function ipow(int $base, int $exp): int
{
    $r = 1;
    for ($i = 0; $i < $exp; $i++) {
        $r *= $base;
    }
    return $r;
}

function isArmstrong(int $number): bool
{
    if ($number <= 0) {
        return false;
    }

    // Count digits k
    $k = 0;
    $t = $number;
    while ($t > 0) {
        $k++;
        $t = intdiv($t, 10);
    }

    // Sum digit^k
    $t = $number;
    $sum = 0;
    while ($t > 0) {
        $d = $t % 10;
        $sum += ipow($d, $k);
        $t = intdiv($t, 10);
    }

    return $sum === $number;
}

$number = 153;
echo isArmstrong($number)
    ? $number . " is an Armstrong number."
    : $number . " is not an Armstrong number.";
?>

Explanation

Two passes over the digits: first to learn k, second to sum dk for each digit d.

if ($number <= 0) return false;

Guard non-positive inputs. This page checks positive integers only.

while ($t > 0) { $k++; $t = intdiv($t, 10); }

Count digits. Integer division by ten strips one digit per iteration.

$sum += ipow($d, $k);

Same exponent for every digit. That is the core Armstrong rule.

return $sum === $number;

Final comparison against the original number.

2

Armstrong numbers in a range

Same isArmstrong helper as Example 1, wrapped in a loop from 1 to 200.

php
<?php
function ipow(int $base, int $exp): int
{
    $r = 1;
    for ($i = 0; $i < $exp; $i++) {
        $r *= $base;
    }
    return $r;
}

function isArmstrong(int $number): bool
{
    if ($number <= 0) return false;

    $k = 0;
    $t = $number;
    while ($t > 0) { $k++; $t = intdiv($t, 10); }

    $t = $number;
    $sum = 0;
    while ($t > 0) {
        $d = $t % 10;
        $sum += ipow($d, $k);
        $t = intdiv($t, 10);
    }
    return $sum === $number;
}

$start = 1;
$end = 200;
echo "Armstrong numbers in the range $start to $end:\\n";
for ($i = $start; $i <= $end; $i++) {
    if (isArmstrong($i)) echo $i . " ";
}
?>

Explanation

The outer loop tries every number in the interval; the inner test processes digits.

for ($i = $start; $i <= $end; $i++)

Brute enumeration. Change $start and $end to your own bounds.

if (isArmstrong($i)) echo $i . " ";

Filter using the same predicate as the single-number program.

Optimization

Exponentiation table. For a fixed digit count k, precompute 0^k .. 9^k and replace repeated power loops with a lookup.

Bounds on sums. For digit length k, the maximum possible sum is 9^k * k. This can help prune searches when generating large lists.

Wide integers. For larger values, keep the running sum in a wider type when possible and be aware of integer overflow limits.

Interview: explain the O(log n) digit passes clearly; mention lookup tables only if asked about fast range generation.

❓ FAQ

In base 10, a positive integer n is an Armstrong number (also called narcissistic) if n equals the sum of its decimal digits, each raised to the power of the total number of digits. Example: 153 has three digits and 1^3 + 5^3 + 3^3 = 153.
Yes. For a one-digit n, the digit count is 1, and n^1 = n, so every digit 1 through 9 is Armstrong. Whether to include 0 depends on the problem statement; this page treats n <= 0 as not Armstrong.
pow() works with floating-point numbers in many cases. For exact equality checks, integer multiplication in a loop (or a small lookup table) avoids rounding surprises.
Definitions vary. The sample programs return false for n <= 0 so digit counting stays well-defined and matches common interview specs that focus on positive integers.
Let d be the number of decimal digits. Counting digits and summing digit powers are both O(d), and d is Theta(log n). So one check is O(log n) in base 10.
The sum of digit powers can get large. PHP integers are platform-dependent; on 64-bit they are usually safe for typical interview ranges, but extremely large values can overflow.

🔄 Input / output examples

For the single-number program with a literal $number, typical lines look like this.

Value of $numberTypical line printed
153153 is an Armstrong number.
123123 is not an Armstrong number.
77 is an Armstrong number.
00 is not an Armstrong number. (with the sample guard)

For the range program with $start = 1 and $end = 200:

Console
Armstrong numbers in the range 1 to 200:
1 2 3 4 5 6 7 8 9 153

Edge cases and pitfalls

Most bugs come from miscounting digits, losing the original value, or using floating-point powers.

Input

n ≤ 0

Return false early. Otherwise 0 can slip through with a digit count of 0 in naive loops.

State

Losing the original n

Keep a copy for the final comparison and use temporaries for counting and summing.

Floats

pow() rounding

Casting float results back to int can be off by one. Integer multiplication is safest for exact checks.

Overflow

Partial sums

Digit powers can add up quickly. Be aware of integer limits if you push input sizes very high.

⏱️ Time and space complexity

TaskTimeExtra space
Single isArmstrong(n) (two digit passes)O(log n)O(1)
Range scan [1, U]roughly O(U log U)O(1)

Auxiliary memory beyond the call stack is a handful of integers in both examples.

Summary

  • Definition: sum of each digit raised to the digit-count power equals n.
  • Implementation: count digits, sum integer powers, compare to the original n, and guard n ≤ 0.
  • Watch-outs: avoid float rounding, watch overflow, and keep the original value unchanged.
Did you know?

Besides the one-digit cases 19, the only three-digit Armstrong numbers are 153, 370, 371, and 407. For example, 1³ + 5³ + 3³ = 153.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful