PHP program to print sum of digits of a number

To print sum of digits of a number we have to add all digits of a number.

For Example :
96532 = 9+6+5+3+2 = 25

Logic :

  1. Get the number.
  2. Divide the number by 10
  3. Add the remainder to a variable
  4. Repeat the process until remainder is 0

PHP program to print sum of digits of a number :

<?php
/*******************************

 ###  PHP program to print sum of digits of a number ###
 
  #####  https://bptutorials.com #####

******************************/




$number = 96532; // Input value by user
$sum=0; $remainder=0; 
  for ($i =0; $i<=strlen($number);$i++) 
 { 
  $remainder=$number%10; 
  $sum = $sum + $remainder; 
  $number=$number/10; 
  } 
 echo "Sum of digits 96532 is $sum"; 
?> 

Output :

Sum of digits 96532 is 25 
PHP program to print sum of digits of a number
Share This!

Leave a Reply

Your email address will not be published.