We can use math modulus to get the reminder of division by 10 and use it to get all digits. We are using floor() also.
Sum of all digits of a number in PHP by extracting digits and by using sticky form
$n1=1234321; // Sample number
$sum=0;
while($n1>0){
$d=$n1%10; // reminder of division
$sum = $sum + $d;
//$n1=floor($n1/10); // floor value
$n1=$n1/10; // integer output as both are integers
}
echo $sum;
Output
16
User input in a form
We can ask user input and by using a sticky form and collect the number to get the sum of the digits.
<form method=POST action=''>
<input type=text name=n1 value='$n1'>
<input type=submit value=Submit>
</form>";
$n2=$n1; // to display along with sum
$sum=0;
while($n1>0){
$d=$n1%10; // reminder
$sum=$sum+$d;
//$n1=floor($n1/10);
$n1=$n1/10; // integer output as both are integers
}
echo " Sum of digits of $n2 is $sum";
We can use number ( or string ) as string and get the sum of the digits.
$n1='4568'; // use string, not as number.
//$n1=4568; // using a number . use next line also
//$n1=$n1.""; // converting to string
$length=strlen($n1);
$sum=0;
for($i=0;$i<$length;$i++){
$sum=$sum+$n1[$i];
}
echo "Sum of digits of $n1 : ".$sum;