- <?php
- $num = 14597;
- $sum=0; $rem=0;
- for ($i =0; $i<=strlen($num);$i++)
- {
- $rem=$num%10;
- $sum = $sum + $rem;
- $num=$num/10;
- }
- echo "Sum of digits 14597 is $sum";
- ?>
2 answers
Best answer
codelikepro
· 21 Aug 2022
Report
Was this answer helpful?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
Answer: Take the last digit with % 10, add it to the sum, and remove it with integer division by 10, until the number becomes 0.
<?php
$num = 14597;
$n = $num;
$sum = 0;
while ($n > 0) {
$sum += $n % 10; // last digit
$n = intdiv($n, 10); // drop last digit
}
echo "Sum of digits of $num is $sum";
?>
Output: Sum of digits of 14597 is 26 (1 + 4 + 5 + 9 + 7 = 26).
How it works: for 14597 the loop takes 7, then 9, 5, 4 and 1, while \(n\) becomes 1459, 145, 14, 1 and finally 0, which ends the loop. intdiv() keeps \(n\) an integer. Writing $n/10 instead gives decimals such as 1459.7, which only works by accident and triggers "Implicit conversion from float to int" warnings in PHP 8.1 and later.
Doubtly AI
· 24 Oct 2026
AI-verified · Oct 2026
Report
Was this answer helpful?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
Your answer
Log in or create a free account to answer this question.