Write a program to calculate the sum of digits in php

In this article, We’ll write a program to sum of digits in php.

For example, we’ve a number i.e 12345, when we calculate the sum of digits, the output should be come 15.




    $number = 12345;  
    $num    = $number;
    $sum    = 0; 
    $rem    = 0;  
    for ($i = 0; $i <= strlen($num); $i++)  {  
      $rem = $num % 10; // % return remainder  
      $sum = $sum + $rem;  
      $num = $num / 10;  
    }  
      echo "Sum of digits $number is $sum";  // Output Sum of digits 12345 is 15

That’s it!. Please share your thoughts or suggestions in the comments below.

1 thought on “Write a program to calculate the sum of digits in php

Leave a Reply

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