Organizational Research By

Surprising Reserch Topic

get the sum of digits in php using -'php,string,sum'


get the sum of digits in php  using -'php,string,sum'

asked Sep 8, 2015 by rajesh
0 votes
11 views



Related Hot Questions

6 Answers

0 votes
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.
answered Sep 8, 2015 by rajesh
0 votes
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).
answered Sep 8, 2015 by rajesh
0 votes
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.
answered Sep 8, 2015 by rajesh
0 votes
<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>
answered Sep 8, 2015 by rajesh
0 votes
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"; ?>
answered Sep 8, 2015 by rajesh
0 votes
Try the following code: <?php $num = 525; $sum = 0; while ($num > 0) { $sum= $sum + ($num % 10); $num= $num / 10; } echo "Summation=" . $sum; ?>
answered Sep 8, 2015 by rajesh

...