PHP Program for Sum of Digits Using Recursion
function sumDigits($n) { if ($n == 0) return 0; return $n % 10 + sumDigits(intval($n / 10)); } which adds the last digit to the sum of the remaining digits recursively.Examples
How to Think About It
% to get the last digit, and integer division / to remove it. Keep calling the function with the smaller number until it reaches zero, then add all digits together.Algorithm
Code
<?php function sumDigits($n) { if ($n == 0) { return 0; } return $n % 10 + sumDigits(intval($n / 10)); } $number = 12345; echo "Sum of digits of $number is: " . sumDigits($number); ?>
Dry Run
Let's trace sumDigits(123) through the code
Initial call
sumDigits(123): last digit = 123 % 10 = 3, call sumDigits(12)
Second call
sumDigits(12): last digit = 12 % 10 = 2, call sumDigits(1)
Third call
sumDigits(1): last digit = 1 % 10 = 1, call sumDigits(0)
Base case
sumDigits(0): return 0
Return from third call
1 + 0 = 1
Return from second call
2 + 1 = 3
Return from initial call
3 + 3 = 6
| Call | Number | Last Digit | Recursive Call | Return Value |
|---|---|---|---|---|
| 1 | 123 | 3 | sumDigits(12) | 6 |
| 2 | 12 | 2 | sumDigits(1) | 3 |
| 3 | 1 | 1 | sumDigits(0) | 1 |
| 4 | 0 | - | - | 0 |
Why This Works
Step 1: Base Case
The function stops calling itself when the number becomes 0, returning 0 to end recursion.
Step 2: Extract Last Digit
Using % 10 gets the last digit of the number to add to the sum.
Step 3: Recursive Call
The function calls itself with the number divided by 10 (removing the last digit) to process the remaining digits.
Alternative Approaches
<?php function sumDigitsString($n) { $digits = str_split($n); $sum = 0; foreach ($digits as $digit) { $sum += intval($digit); } return $sum; } $number = 12345; echo "Sum of digits (string method) of $number is: " . sumDigitsString($number); ?>
<?php function sumDigitsTail($n, $acc = 0) { if ($n == 0) { return $acc; } return sumDigitsTail(intval($n / 10), $acc + $n % 10); } $number = 12345; echo "Sum of digits (tail recursion) of $number is: " . sumDigitsTail($number); ?>
Complexity: O(d) time, O(d) space
Time Complexity
The function calls itself once per digit, so time grows linearly with the number of digits d.
Space Complexity
Each recursive call adds a layer to the call stack, so space also grows linearly with d.
Which Approach is Fastest?
Iterative or string-based methods use constant space and are faster in practice, but recursion is clearer for learning.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(d) | O(d) | Learning recursion and clarity |
| Iterative (string) | O(d) | O(1) | Performance and simplicity |
| Tail Recursion | O(d) | O(d) | Conceptual optimization, but no PHP tail call optimization |