How to use a loop to extract digits one by one In PHP
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
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