Sum of array in PHP
In this post, you will learn how to find the sum of an array using the PHP programming language.
In the development process, we may come to a situation where we need to calculate the sum of all the elements of an array. Such a type of logical question may be asked in a programming interview or competitive exams. Here, we mention different ways to calculate the sum of an array in PHP.
Sum of elements in an array using array_sum() function
The array_sum() function of PHP returns the sum of all the numeric values in an array.
Syntax-array_sum(array)
<?php
$sum = array(7, 45, 9, 3);
echo "Sum of array elements : ";
echo array_sum($sum);
?>
Output of the above code:
Sum of array elements : 64
Sum of array in PHP using for loop
In the given PHP program, we have calculated the sum of all the array elements of the given array using the for loop.
<?php
$arr = array(10, 7, 5, 3, 6);
$sum = 0;
for ($i = 0; $i < count($arr); $i++) {
$sum = $sum + $arr[$i];
}
print("Sum of all the elements : " . $sum);
?>
Output of the above code:
Sum of all the elements : 31
Sum of array in PHP using forEach
In the given PHP program, we have calculated the sum of all the array elements of the given array using foreach.
<?php
$arr = array(12, 8, 5, 2, 4);
$sum = 0;
foreach ($arr as $value) {
$sum +=$value;
}
print("Sum of all the elements : " . $sum);
?>
Output of the above code:
Sum of all the elements : 31
Related Articles
PHP reverse a string without predefined functionPHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
PHP calculate percentage of total
PHP sanitize input for MySQL
Display PDF using an AJAX call
How to fetch data from database in php and display in pdf
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Sending HTML form data to an email address