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";
}
?>

Leave a Reply

Related Posts: You may like

Find Armstrong Number

Write a program find Factorial of a number

Write a PHP program to Print table of Number

Write a PHP program to print prime number

PHPKIDA Offering Free Tools:

INSTA DOWNLOADER

Download Instagram Videos & Photos.

Download Now

CURRENCY CONVERTER

Real Time Currency Converter

Convert Now

ROBOST.TXT GEN.

Robots.txt File Creater

Create Now

HTML MINIFIER

Compress yout HTML Code

Minify Now

CSS MINIFIER

Compress yout CSS Code

Minify Now

JAVASCRIPT MINIFIER

Compress yout JavaScript Code

Minify Now

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.