Thursday, October 16, 2025
HomeLanguagesPHP array_sum() Function

PHP array_sum() Function

The array_sum() function returns the sum of all the values in an array(one dimensional and associative). It takes an array parameter and returns the sum of all the values in it.

number array_sum ( $array )

Argument
The only argument to the function is the array whose sum needs to be calculated.

Return value
This function returns the sum obtained after adding all the elements together. The returned sum may be integer or float. It also returns 0 if the array is empty.

Examples:

Input : $a = array(12, 24, 36, 48);
        print_r(array_sum($a));
Output :120

Input : $a = array();
        print_r(array_sum($a));
Output :0

In the first example the array calculates the sum of the elements of the array and returns it. In the second example the answer returned is 0 since the array is empty.

Program – 1




<?php
//array whose sum is to be calculated
$a = array(12, 24, 36, 48);
  
//calculating sum
print_r(array_sum($a));
?>


Output:

120

Program – 2




<?php
//array whose sum is to be calculated
$a = array();
  
//calculating sum
print_r(array_sum($a));
?>


Output:

0

Program – 3




<?php
// array whose sum is to be calculated
$b = array("anti" => 1.42, "biotic" => 12.3, "charisma" => 73.4);
  
// calculating sum
print_r(array_sum($b));
?>


Output:

87.12

Thanks to HGaur for providing above examples.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS