PHP sum of array elements
In this tutorial, we will code the PHP program to sum the array of elements.PHP Simple Sum of Array Elements
Here, we will code the PHP program simply to sum the array of elements.
1 2 3 4 5 6 7 8 |
<html> <body> <?php $a=array(5,15,25); echo array_sum($a); ?> </body> </html> |
PHP Simple Sum of Array Elements
Here, we will code the PHP program to sum the array of elements by using them for a loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <body> <?php $series; $sum=0; $num=10; for($series=1;$series<=$num;$series++) { $sum= $sum+$series; echo $series; } echo "<br/> sum= : ".$sum; ?> </body> </html> |
PHP Sum of Array Elements with Form Values entered by the User
Here, we will code the PHP program to sum the array of elements by using the form values that will be entered by the user. 1st file: index.php 2nd file: sumaction.php Now, let’s see the code of the first file named as index.php.
1 2 3 4 5 6 7 8 |
<html> <body> <form method="POST" action="sumaction.php"> Please enter number for sum<input type="text" name="num"><br/> <input type="submit" name="sub" value="calculator"> </form> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 |
<?php $my_num = $_POST['num']; $sum=0; $rem; for($i=0;$i<=strlen($my_num); $i++) { $rem=$my_num%10; $sum=$sum+$rem; $my_num=$my_num/10; } echo "Sum of digits is $sum"; ?> |

PHP Sum of digits
Here, we will code the PHP program to sum all digits of a number. For example, if the number is 234, then it will ad the numbers as 2+3+4=9.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html> <body> </body> </html> <?php $num=134; $sum=0; $rem; for($i=0;$i<=strlen($num); $i++) { $rem=$num%10; $sum=$sum+$rem; $num=$num/10; } echo "Sum of digits 134 is $sum"; ?> |