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.

9 thoughts on “Write a program to calculate the sum of digits in php

  1. Hi! This is my first visit to your blog! We are a group of
    volunteers and starting a new initiative in a community in the same niche.

    Your blog provided us useful information to work on.
    You have done a wonderful job!

    Keep up the good work!

Leave a Reply

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