How to find Sum the Digits of a given Number in PHP ?
We will explore how to find the sum of the digits of a given number in PHP. This task involves extracting each digit from the number and adding them together to get the final sum.
Table of Content
- Using a loop to extract digits one by one
- Using mathematical operations to extract digits
Using a loop to extract digits one by one
In this approach, we are using a for loop to iterate over each character in the digit. First, we will convert the number to a string to easily access each digit. Then we will iterate over each character in the string. Convert each character back to a number and add it to a running sum.
Example: The below example uses for loop to to find the sum of the digits of a given number in PHP.
<?php
// function to calculate sum of digits
function sumDigits($number) {
$sum = 0;
// converting number to string to access digits easily
$numberStr = (string)$number;
for ($i = 0; $i < strlen($numberStr); $i++) {
$digit = (int)$numberStr[$i];
$sum += $digit;
}
return $sum;
}
$number = 12345;
echo "Sum of digits: " . sumDigits($number);
?>
Output
Sum of digits: 15
Using mathematical operations to extract digits
In this approach, we are using mathematical operations to calculate sum of digits of numbers. First we use modulus operator (%) to extract the last digit of the number then add that extracted digit to a running sum. Then divide the number by 10 to remove the last digit. We will repeat the above steps until the number becomes 0.
Example: This example uses mathematical operations to find the sum of the digits of a given number in PHP.
<?php
function sumDigits($number) {
$sum = 0;
while ($number != 0) {
$digit = $number % 10;
$sum += $digit;
$number = (int)($number / 10);
}
return $sum;
}
$number = 76534;
echo "Sum of digits: " . sumDigits($number);
?>
Output
Sum of digits: 25