31

How do I find the sum of all the digits in a number in PHP?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Leticia Meyere
  • 319
  • 1
  • 3
  • 3

13 Answers13

117
array_sum(str_split($number));

This assumes the number is positive (or, more accurately, that the conversion of $number into a string generates only digits).

Artefacto
  • 96,375
  • 17
  • 202
  • 225
  • Thank you! The simpler, the better! If you don't know whether a number is positive or negative, you could use the abs() function to make it always positive array_sum(str_split(abs($number))); – imelgrat Sep 21 '16 at 15:52
  • Funny how this got 70+ votes here and on php manual page it gets downvoted by -40 [see here](http://php.net/manual/en/function.array-sum.php#121020) – Manuel Mannhardt Mar 07 '18 at 13:06
  • It´s not only shorter than any loop, but also faster: PHP has no integer division, so a looping solution has to cast the remaining number from float to int in every iteration. – Titus May 04 '18 at 15:48
13

Artefactos method is obviously unbeatable, but here an version how one could do it "manually":

$number = 1234567890;
$sum = 0;
do {
    $sum += $number % 10;
}
while ($number = (int) ($number / 10));

This is actually faster than Artefactos method (at least for 1234567890), because it saves two function calls.

NikiC
  • 100,734
  • 37
  • 191
  • 225
4

Another way, not so fast, not single line simple

<?php

    $n = 123;
    $nstr = $n . "";

    $sum = 0;
    for ($i = 0; $i < strlen($nstr); ++$i)
    {
        $sum += $nstr[$i];
    }
    echo $sum;

?>

It also assumes the number is positive.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
3
function addDigits($num) {

    if ($num % 9 == 0 && $num > 0) {
        return 9;
    } else {
          return $num % 9;
        }
    }

only O(n)

at LeetCode submit result: Runtime: 4 ms, faster than 92.86% of PHP online submissions for Add Digits. Memory Usage: 14.3 MB, less than 100.00% of PHP online submissions for Add Digits.

Aries
  • 31
  • 2
1
<?php 
// PHP program to calculate the sum of digits 
function sum($num) { 
    $sum = 0; 
    for ($i = 0; $i < strlen($num); $i++){ 
        $sum += $num[$i]; 
    } 
    return $sum; 
} 

// Driver Code 
$num = "925"; 
echo sum($num); 
?> 

Result will be 9+2+5 = 16

  • Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 21 '20 at 00:39
0

Try the following code:

<?php

$num = 525;
$sum = 0;

while ($num > 0)
{
    $sum= $sum + ($num % 10);
    $num= $num / 10;
}
echo "Summation=" . $sum;

?>
kenorb
  • 155,785
  • 88
  • 678
  • 743
Mayank Dudakiya
  • 3,635
  • 35
  • 35
0

If interested with regex:

array_sum(preg_split("//", $number));
itsazzad
  • 6,868
  • 7
  • 69
  • 89
0
    <?php
echo"----Sum of digit using php----";
echo"<br/ >";
$num=98765;
$sum=0;
$rem=0;
for($i=0;$i<=$num;$i++)
{
$rem=$num%10;
$sum=$sum+$rem;
$num=$num/10;
}
echo "The sum of digit 98765 is ".$sum;
?>
-----------------Output-------------
----Sum of digit using php----
The sum of digit 98765 is 35
0
// math before code 

// base of digit sums is 9 

// the product of all numbers multiplied by 9 equals 9 as digit sum

$nr = 58821.5712; // any number

// Initiallization 

$d = array();

$d = explode(".",$nr); // cut decimal digits

$fl = strlen($d[1]); // count decimal digits

$pow = pow(10 ,$fl); // power up for integer

$nr = $nr * $pow; // make float become integer

// The Code

$ds = $nr % 9; // modulo of 9 

if($ds == 0) $ds=9; // cancel out zeros

echo $ds;
scopchanov
  • 7,966
  • 10
  • 40
  • 68
stereoIII6
  • 11
  • 2
-1

Assume you want to find the sum of the digits of a number say 2395 the simplest solution would be to first split the digits and find out the sum then concatenate all the numbers into one single number.

<?php
    $number=2;
    $number1=3;
    $number2=9;
    $number3=5;
    $combine=$number.$number1.$number2.$number3;
    $sum=$number+$number1+$number2+$number3;
    echo "The sum of $combine is $sum";
     ?>
-1

One way of getting sum of digit however this is a slowest route.

$n=123;
while(($n=$n-9)>9);
echo "n: $n";
cfnerd
  • 3,658
  • 12
  • 32
  • 44
-2
<html>
<head>
<title>detail</title>
</head>
<body>
<?php
$n = 123;
$sum=0; $n1=0;

  for ($i =0; $i<=strlen($n);$i++)
 {

  $n1=$n%10;

   $sum += $n1;
   $n=$n/10;
  }
 echo $sum;

 ?>
 </body>
</html>
-2

Here's the code.. Please try this

   <?php 
    $d=0;
   $num=12345;

   $temp=$num;

   $sum=0;

   while($temp>1)

     {
      $temp=$temp/10;

        $d++;
         }

     echo "Digits Are : $d </br>";

      for (;$num>1;)

             {
              $d=$num%10;

             $num=$num/10;

             $sum=$sum+$d;

             }

           echo "Sum of Digits is : $sum";

   ?>
The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53