0
0
PhpProgramBeginner · 2 min read

PHP Program for Sum of Digits Using Recursion

You can find the sum of digits of a number in PHP using recursion by defining a function like 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

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits using recursion, think of the number as made of its last digit plus the rest. Use the remainder operator % 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

1
Check if the number is 0; if yes, return 0 as the sum.
2
Find the last digit by taking the number modulo 10.
3
Call the function recursively with the number divided by 10 (integer division).
4
Add the last digit to the result of the recursive call.
5
Return the total sum.
💻

Code

php
<?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);
?>
Output
Sum of digits of 12345 is: 15
🔍

Dry Run

Let's trace sumDigits(123) through the code

1

Initial call

sumDigits(123): last digit = 123 % 10 = 3, call sumDigits(12)

2

Second call

sumDigits(12): last digit = 12 % 10 = 2, call sumDigits(1)

3

Third call

sumDigits(1): last digit = 1 % 10 = 1, call sumDigits(0)

4

Base case

sumDigits(0): return 0

5

Return from third call

1 + 0 = 1

6

Return from second call

2 + 1 = 3

7

Return from initial call

3 + 3 = 6

CallNumberLast DigitRecursive CallReturn Value
11233sumDigits(12)6
2122sumDigits(1)3
311sumDigits(0)1
40--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

Using string conversion and iteration
php
<?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);
?>
This method converts the number to a string and sums digits using a loop, which is simpler but not recursive.
Using tail recursion with helper function
php
<?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);
?>
Tail recursion uses an accumulator to hold the sum, which can be optimized by some compilers but PHP does not optimize tail calls.

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.

ApproachTimeSpaceBest For
RecursiveO(d)O(d)Learning recursion and clarity
Iterative (string)O(d)O(1)Performance and simplicity
Tail RecursionO(d)O(d)Conceptual optimization, but no PHP tail call optimization
💡
Always include a base case in recursion to avoid infinite loops.
⚠️
Beginners often forget to convert the division result to an integer, causing infinite recursion.