Pawan_Agarwal Posted June 16, 2013 Share Posted June 16, 2013 I want to add the number with this code while($i>0) { $j=$i%10; $i=$i/10; $sum=$sum+$j; } I have number in $i=12345, now after execution, sum must return the sum of all digits of its number 15 Example: $i=23, sum=5 $i=18, sum=9 $i=19, sum=10 As you can see the code must terminate as soon as $i==0, but I am facing infinite loop........thanks Link to comment https://forums.phpfreaks.com/topic/279231-sum-of-number/ Share on other sites More sharing options...
kicken Posted June 16, 2013 Share Posted June 16, 2013 Seems to work fine for me. One thing you could change is to ensure $i is an int. $i=12345; while($i>0) { $j=$i%10; $i=intval($i/10); $sum=$sum+$j; } var_dump($sum); Link to comment https://forums.phpfreaks.com/topic/279231-sum-of-number/#findComment-1436240 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.