your image

PHP Sum of Digits Program - javatpoint

javapoint
Related Topic
:- PHP Java

Sum of Digits

To find sum of digits of a number just add all the digits.

For example,

  1. 14597 = 1 + 4 + 5 + 9 + 7  
  2. 14597 = 26  

Logic:

  • Take the number.
  • Divide the number by 10.
  • Add the remainder to a variable.
  • Repeat the process until remainder is 0.

Example:

 

3. PHP Inheritance | Build a CMS using OOP PHP tutorial MVC [2020]

Given program shows the sum of digits of 14597.

  1. <?php  
  2. $num = 14597;  
  3. $sum=0; $rem=0;  
  4.   for ($i =0; $i<=strlen($num);$i++)  
  5.  {  
  6.   $rem=$num%10;  
  7.    $sum = $sum + $rem;  
  8.    $num=$num/10;  
  9.   }  
  10.  echo "Sum of digits 14597 is $sum";  
  11.  ?>  

Output:

Comments