How to use mathematical operations to extract digits In PHP
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
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