mid_knight Posted October 10, 2008 Share Posted October 10, 2008 PHP newbie! I've looked through the forums, but couldn't find anything that helps me with my problem. I'm trying to write the code for a calculation that adds the individual digits in a number, and if the answer comprises more than 1 digit, repeats the formula. I've successfully done this in excel and vb using the MID function, but since I'm new to php I have no idea how to proceed. I tend to gather substr() would be useful here. The logic of the calculation is as follows: (1) Determine if the length of the number exceeds 1 ... else just use the number (2) Loop from the first digit to the last digit (as determined by the length) adding each digit (3) Assign the calculated number as the new number and start again at step 1. This iteration repeats until a single digit remains which becomes the final number for use. It would be unfair for me to expect anyone to write the code for me (although I wouldn't mind ), but a few hints on how to proceed with the code would be great. Thanks in advance. Quote Link to comment https://forums.phpfreaks.com/topic/127869-calculate-digits-in-number/ Share on other sites More sharing options...
sasa Posted October 10, 2008 Share Posted October 10, 2008 try <?php $a = 1234567; $a = "$a"; while ($a > 9) { $b = 0; for ($i = 0; $i < strlen($a); $i++) $b += $a[$i]; $a = "$b"; } echo $a; ?> Quote Link to comment https://forums.phpfreaks.com/topic/127869-calculate-digits-in-number/#findComment-662086 Share on other sites More sharing options...
mid_knight Posted October 11, 2008 Author Share Posted October 11, 2008 Wow. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/127869-calculate-digits-in-number/#findComment-662563 Share on other sites More sharing options...
ghostdog74 Posted October 11, 2008 Share Posted October 11, 2008 another way $a = 1234567; $a = str_split("$a"); while ( count($a) > 1 ){ $a = str_split(array_sum($a)); } print_r($a); Quote Link to comment https://forums.phpfreaks.com/topic/127869-calculate-digits-in-number/#findComment-662576 Share on other sites More sharing options...
aeonsky Posted October 11, 2008 Share Posted October 11, 2008 Sorry, misunderstood. Edit. Quote Link to comment https://forums.phpfreaks.com/topic/127869-calculate-digits-in-number/#findComment-662595 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.