Write a PHP script that calculates the sum of digits in a given number.

<?php
function sumOfDigits($number) {
    $sum = 0;

    // Convert the number to a string to iterate through each digit
    $digits = str_split((string)$number);

    foreach ($digits as $digit) {
        $sum += (int)$digit;
    }

    return $sum;
}

$testNumber = 456;
$digitSum = sumOfDigits($testNumber);

echo "The sum of digits in $testNumber is: $digitSum";
?>
  • The script defines a function sumOfDigits that takes a number as input and calculates the sum of its digits.
  • It converts the number to a string using (string)$number and then uses str_split to create an array of individual digits.
  • The foreach loop iterates through each digit, converting it back to an integer and adding it to the sum.
  • The script then calls the function with a sample number ($testNumber) and prints the result.

Post your Answer