tags:

views:

128

answers:

3

How do I find the sum of all the digits in a number in PHP? I've found solutions for C# and others, but not PHP. How do I do it? Thanks!

+27  A: 
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
Thanks, that is like insanely simple!
Leticia Meyere
+1 for doing it in 2 functions.
Kieran Allen
+1 for ingenious solution.
nikic
+1 because I had to change my shorts after I read this
abelito
+3  A: 

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
+1 for efficiency.
Frank Farmer
+5  A: 

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
+1, clever use!
alex