PHP Program to Find Sum of Digits of a Number
$sum = 0; foreach (str_split($num) as $digit) { $sum += (int)$digit; }.Examples
How to Think About It
% and removing it using / until the number is zero.Algorithm
Code
<?php $num = 123; $sum = 0; while ($num > 0) { $digit = $num % 10; $sum += $digit; $num = (int)($num / 10); } echo $sum; ?>
Dry Run
Let's trace the number 123 through the code to find the sum of its digits.
Initial values
$num = 123, $sum = 0
First iteration
digit = 123 % 10 = 3; sum = 0 + 3 = 3; num = 123 / 10 = 12
Second iteration
digit = 12 % 10 = 2; sum = 3 + 2 = 5; num = 12 / 10 = 1
Third iteration
digit = 1 % 10 = 1; sum = 5 + 1 = 6; num = 1 / 10 = 0
Loop ends
num is now 0, loop stops; final sum = 6
| Iteration | num | digit | sum |
|---|---|---|---|
| 1 | 123 | 3 | 3 |
| 2 | 12 | 2 | 5 |
| 3 | 1 | 1 | 6 |
Why This Works
Step 1: Extract each digit
Using % 10 gets the last digit of the number because it gives the remainder when divided by 10.
Step 2: Add digit to sum
We add the extracted digit to the running total stored in $sum.
Step 3: Remove last digit
Dividing the number by 10 and taking the integer part removes the last digit, preparing for the next loop iteration.
Alternative Approaches
<?php $num = 123; $sum = 0; foreach (str_split((string)$num) as $digit) { $sum += (int)$digit; } echo $sum; ?>
<?php function sumDigits($num) { if ($num == 0) return 0; return ($num % 10) + sumDigits((int)($num / 10)); } echo sumDigits(123); ?>
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits.
Space Complexity
Only a few variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
The modulus and division loop is fastest and uses least memory; string conversion is simpler but uses extra space; recursion is elegant but less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulus and division loop | O(n) | O(1) | Performance and low memory |
| String conversion and loop | O(n) | O(n) | Readability and simplicity |
| Recursive function | O(n) | O(n) | Learning recursion and elegance |
% 10 to get the last digit and integer division to remove it.