PUBLISHED ON: AUGUST 4, 2021
How to calculate the sum of values in an array in PHP?
Answer: Using array_sum()
function
We can calculate the sum of array elements using the PHP predefined array_sum()
function. This function takes the array name as its value and returns the sum of all the elements present within that particular array.
Example: PHP array_sum()
function
In the given example, we have calculated the sum of all the array elements of the given array named $arr
using the PHP predefined array_sum()
function.
<!DOCTYPE html>
<html>
<head>
<title>Calculate the sum of values in an array </title>
</head>
<body>
<?php
$arr = array(2, 6, 3, 7, 8, 12, 76, 89);
$total = array_sum($arr);
echo $total;
?>
</body>
</html>
Sum of all the array elements is: 203
Apart from using a predefined PHP function, we can also calculate the sum of all the elements of an array using for loop.
Example: Using for loop
In the given example, we have calculated the sum of all the array elements of the given array $arr
using for loop.
<!DOCTYPE html>
<html>
<head>
<title>Calculate the sum of values in an array </title>
</head>
<body>
<?php
$arr = array(2, 6, 3, 7, 8, 12, 76, 89);
$total = 0;
for ($i = 0; $i < count($arr); $i++) {
$total = $total + $arr[$i];
}
print("Sum of all the elements is: " . $total);
?>
</body>
</html>
Sum of all the array elements is: 203
Conclusion
In this lesson, we have learned how to calculate the sum of all the array elements in PHP. We discussed two methods. At first, we have calculated the sum of all the array elements using the array_sum()
function, and second we used the for loop
for calculating the sum of all the elements of an array.