Armstrong Numbers in PHP

An Armstrong number, also known as a narcissistic number, is a number that is equal to the sum of the cubes of its digits. Here’s a PHP example to determine if a number is an Armstrong number:

Example of Mathamatics:

153 = (1*1*1) + (5*5*5) + (3*3*3)
153 = 1 + 125 + 27
153 = 153
It means it’s an Armstrong number.

PHP Example:

<?php
function isArmstrong($number)
{
    $total = 0;
    $tempNumber = $number;

    while (floor($tempNumber)) {
        $remainder = $tempNumber % 10;
        $total += $remainder * $remainder * $remainder;
        $tempNumber = $tempNumber / 10;
    }

    return $number == $total;
}

// Allow user input for dynamic Armstrong number checking.
$userInput = 153;

if (isArmstrong($userInput)) {
    echo "$userInput is an Armstrong number";
} else {
    echo "$userInput is not an Armstrong number";
}
?>

Output:

The above PHP code will produce the following output:

 153 is an Armstrong number

Explanation:

  1. Variable Initialization:
    • $number: The number to be checked for being an Armstrong number.
    • $total: The variable to store the sum of the cubes of its digits.
    • $tempNumber: A temporary variable to preserve the original number for comparison.
  2. Loop Logic:
    • The while loop extracts digits one by one, cubes them, and accumulates the result in $total.
  3. Main Logic:
    • Compares the calculated total with the original number to determine if it’s an Armstrong number.