# PHP Program to find sum of individual digits of a Number

In this PHP tutorial, you are going to learn how to write a PHP program to print the sum of individual digits of a given number.

## How to find sum of individual digits of a Number in PHP

To find the sum of individual digits of a given number, we just need to know how to add numbers it’s pretty simple.

Here we first divide our given number into individual digits and then add them all.

In our general life, we are not gonna use such a kind of program but it can be a good exercise for beginners to better understand the PHP loops concept its a very good beginning program.

Let us take our input is 345 then our output would a be something like 12

It’s just simply no creepy maths tricks needed it’s just 3+4+5=12 that’s it.

### Algorithm:

- First, we have to create an HTML code to accept input as we canâ€™t accept input directly by PHP.
- Open PHP by using <?php.
- Create variables to store values which are sent from HTML code let it be “a”.
- Then create a variable and assign it to 0, which would be our sum of numbers let us consider as “sum”.
- Now here comes the heart of this code the logic to implement the code create a while loop with condition as the input variable not equal to 0.(now the code within the loop will repeat till the input variable is set 0)
- Now create a variable to store the remainder of our input when divided by 10 as it would be our first number and last digit of our given number.
- Update the “a” value to a/10 as it would be the remaining number after separating the last number from it.
- Now update sum to sum plus rem.
- Close the while loop.
- Print the sum value, and close the loop.
- That’s it our program is ready to execute.

### Program: sum of individual digits of a Number in PHP

<html> <body> <form method="POST"> Enter the number for which you want to know the sum of digits:<input type="number" name="no"><br> <input type="submit" name="submit"> </form> </body> </html> <?php error_reporting(0); $a=$_POST['no']; if(isset($_POST['submit'])) { $sum=0; while($a!=0) { $rem=$a%10; $a=$a/10; $sum=$sum+$rem; } echo $sum; } ?>

### Output:

Enter the number for which you want to know the sum of digits: 3455 {submit} //after clicking the submit button// 17

You can also read:

## Leave a Reply