When the input is already a digit string, iterating over the characters is simple and avoids numeric conversion. For an integer-only exercise, use modulus with intdiv().
<?php
$digits = '4568';
$sum = 0;
foreach (str_split($digits) as $digit) {
$sum += (int) $digit;
}
echo $sum;
?>
$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=intdiv($n1, 10); // remove the right-most digit
}
echo $sum;
Output
16
<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=intdiv($n1, 10); // remove the right-most digit
}
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;
Output
Sum of digits of 4568 : 23
Using a sticky form
$n1=$_POST['n1'] ?? '';
echo "<form method=POST action=''>
<input type=text name=n1 value='$n1'>
<input type=submit value=Submit>
</form>";
$length=strlen($n1);
$sum=0;
for($i=0;$i<$length;$i++){
$sum=$sum+$n1[$i];
}
echo "Sum of digits of $n1 : ".$sum;
Introduction to PHP Factorial of a number Strong Number Fibonacci Series
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.