PHP Code for Sum of Digits – For Beginners

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

For example,

23762 = 2 + 3 + 7 + 6 + 2
23762 = 20

Logic:

Take the number.

Divide the number by 10.

Add the remainder to a variable.

Repeat the process until remainder is 0.

Example:

Given program shows the sum of digits of 23762.

<?php 

 
$num = 23762;  
$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";  

 ?>  

Leave a Reply

Your email address will not be published. Required fields are marked *