PHP Exercise - Final sum of the digits of a number

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts:107

PHP Exercise - Final sum of the digits of a number

Hi,
I have this php exercise:
- Calculate the final sum of the digits of a number, till get a number with one digit.
For example:

Code: Select all

$nr = 458;
// the code should calculate 4+5+8 = 17, then 1+7 = 8
// result is 8
Any idea, or example?

Admin Posts:805
When you have to repeat multiple times the same operation on a variable, try to build the code based on a recursive function (which auto-calls itself).
Example:

Code: Select all

function getDigitControl($nr) {
  // converts the $nr to string, get array with each digit, get the digits sum
  // if $nr not lower than 10, auto-call this function with the last $nr
  $nr = array_sum(str_split(strval($nr)));
  return ($nr < 10) ? $nr : getDigitControl($nr);
}

$nr = 4512357;
echo getDigitControl($nr);    // 9 

Marius Posts:107
Thank you.
Can you explain this line of code?

Code: Select all

return ($nr < 10) ? $nr : getDigitControl($nr);

MarPlo Posts:186
The syntax:

Code: Select all

condition ? A : B;
is equivalent to:

Code: Select all

if(condition) { then A; }
else { then B; }

sandy Posts:3
Another example with a recursive function:

Code: Select all

<?php
function add($nr) {
  $nr = array_sum(str_split($nr));
  if(strlen($nr) == 1) return $nr;
  else return add($nr);  //good example for recursive function
}
$nr = 852525488;
echo add($nr);
?>