Sum of digits of a number in PHP

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=$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;
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


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











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