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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

120

Program – 2

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

0

Program – 3

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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));
?>

chevron_right


Output:

87.12

Thanks to HGaur for providing above examples.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.