Write a PHP program to print sum of digits

In this program, you will find the Sum of digits program using for loop, while loop, do-while, and HTML form. The Sum of digits is the addition of all individual digits. For example, the sum of digits of 234 is 2+3+4=9

Program to find sum of digit using for loop In PHP


<?php
    $number=345;
    $sum=0;
    for($i=0;$i<=strlen($number);$i++)
    {
        $sum=$sum+$number%10;
        $number/=10;
    }
    echo"sum of digit 345 is $sum";
?>

output

sum of digit 345 is 12

Program to find sum of digit using while loop In PHP


<?php
   $number=123;
   $sum=0;
   while($number>0)
   {
     $sum=$sum+$number%10;
     $number/=10
   }
    echo"sum of digit 123 is $sum";
?>

output

sum of digit 123 is 6

Program to find sum of digit using do-while loop In PHP


<?php
   $number=123;
   $sum=0;
   do
   {
     $sum=$sum+$number%10;
     $number/=10;
   } 
   while($number>0);
   echo"sum of digit 123 is $sum";
?>

output

sum of digit 123 is 6

Find sum of digit using HTML form In PHP


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Write a program to find sum of digit in php</title>
</head>
<body>
    <form>
    <label for="number">Enter the number:</label> <input type="number" name="SumDigit">
    <input type="submit" value="submit" name="click"></br></br>
    </form>
</body>
</html>
<?php
if(isset($_GET["click"]))
{
    $number=$_GET['SumDigit'];
    $num=$number;
    $sum=0;
    for($i=0;$i<=strlen($number);$i++,$number/=10)
    {
        $sum=$sum+$number%10;
    }
    echo"sum of digit $num is $sum";
}
?>

output

Sum of digit program in PHP

Logic to find sum of digits in PHP

  1. Take the number and store it in a variable number.
  2. Find the last digits using modulus division $number%10.
  3. Add the last digit into variable sum.
  4. repeat step 2 and 3 until the value of number become 0.