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
Code: Select all
$nr = 458;
// the code should calculate 4+5+8 = 17, then 1+7 = 8
// result is 8
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
Code: Select all
return ($nr < 10) ? $nr : getDigitControl($nr);
Code: Select all
condition ? A : B;
Code: Select all
if(condition) { then A; }
else { then B; }
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);
?>