Get the sum of digits in PHP

后端 未结 13 2680
攒了一身酷
攒了一身酷 2020-11-29 10:45

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

相关标签:
13条回答
  • 2020-11-29 11:22

    If interested with regex:

    array_sum(preg_split("//", $number));
    
    0 讨论(0)
  • 2020-11-29 11:28

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

    $n=123;
    while(($n=$n-9)>9);
    echo "n: $n";
    
    0 讨论(0)
  • 2020-11-29 11:30

    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";
    
       ?>
    
    0 讨论(0)
  • 2020-11-29 11:34

    Try the following code:

    <?php
    
    $num = 525;
    $sum = 0;
    
    while ($num > 0)
    {
        $sum= $sum + ($num % 10);
        $num= $num / 10;
    }
    echo "Summation=" . $sum;
    
    ?>
    
    0 讨论(0)
  • 2020-11-29 11:38
    <?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

    0 讨论(0)
  • 2020-11-29 11:38
    <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>
    
    0 讨论(0)
提交回复
热议问题