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 Quote Link to comment https://forums.phpfreaks.com/topic/279231-sum-of-number/ Share on other sites More sharing options...
Solution kicken Posted June 16, 2013 Solution 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); Quote Link to comment https://forums.phpfreaks.com/topic/279231-sum-of-number/#findComment-1436240 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.