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
2010-07-12 21:47:03
Thanks, that is like insanely simple!
Leticia Meyere
2010-07-12 21:49:37
+1 for doing it in 2 functions.
Kieran Allen
2010-07-12 22:05:28
+1 for ingenious solution.
nikic
2010-07-12 22:10:56
+1 because I had to change my shorts after I read this
abelito
2010-07-12 22:43:49
+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
2010-07-12 21:53:39
+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
2010-07-12 22:01:45