Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP program to sum the digits in a number
To sum the digits in a number, we can treat the number as a string and iterate through each character, converting it back to an integer and adding to our sum.
Example
<?php
function sum_of_digits($my_num){
$sum = 0;
for ($i = 0; $i < strlen($my_num); $i++){
$sum += $my_num[$i];
}
return $sum;
}
$my_num = "65";
print_r("The sum of digits is ");
echo sum_of_digits($my_num);
?>
Output
The sum of digits is 11
How It Works
The function sum_of_digits takes a number as a parameter. It initializes a variable $sum to 0, then iterates through each character of the number using strlen() to get the length. Each character is automatically converted to an integer when added to the sum.
For the number "65", the function processes:
- First digit: 6 (adds 6 to sum)
- Second digit: 5 (adds 5 to sum)
- Total sum: 6 + 5 = 11
Alternative Method Using Mathematical Approach
<?php
function sum_of_digits_math($num){
$sum = 0;
while ($num > 0) {
$sum += $num % 10;
$num = intval($num / 10);
}
return $sum;
}
$number = 65;
echo "The sum of digits is " . sum_of_digits_math($number);
?>
The sum of digits is 11
Conclusion
Both methods effectively sum the digits of a number. The string approach is simpler to understand, while the mathematical method using modulo and division operations is more traditional in programming.
Advertisements
