Sum of digits of a number in PHP

Current ways to sum the digits

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;
?>

Using modulus

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=intdiv($n1, 10); // remove the right-most digit
}
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=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
Basic Codes Armstrong number Fibonacci Series


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer