Write a PHP program to print sum of digits

Here we are write a program to find sum of digits of a given number, for the sum of digits we have to add all the digits of given number.

Logical Part of program:

1. First you have to take the number.
2. Then divide the taken number by 10.
3. Store the remainder into a variable.
4. Final step repeat the process until remainder is 0.

Given program shows the sum of digits of 987654321.

PHP Logic Part:

1. Creating Three(3) PHP Variables. $num, $sum, $rem.
Variable $num will be store given numbers.
Variable $sum will be store total sum of digits.
Variable $rem will be store remainder of the number.
2. Then here we are using for loop for logical part, withing for loop we also use a php function strlen() to find length of numbers. ;enght of number we are checking with variable $i that was initialize by 0.

PHP Program of sum of digits

<?php
$num = 987654321;
$sum = 0;
$rem = 0;
for ($i =0; $i<=strlen($num);$i++)
{ 
 $rem=$num%10; 
 $sum = $sum + $rem;
 $num=$num/10;
}
echo "Sum of digits $num is $sum"; 
?>

PHP Program of sum of digits using HTML Form

<form method="post">
<input type="text" name="number" placeholder="Enter number" />
<input type="submit" value="Submit" />
</form>

<?php
if(isset($_POST['number']))
{
$onum = $_POST['number'];
$num = $_POST['number'];
$sum = 0;
$rem = 0;
for ($i =0; $i<=strlen($num);$i++)
{
$rem=$num%10;
$sum = $sum + $rem;
$num=$num/10;
}
echo "Sum of digits $onum is $sum";
}
?>
About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.