PHP array_sum() Function

PHP array_sum() function is “used to calculate the sum of all the values in an array(one-dimensional and associative).” 

It returns 0 if the array is empty. The returned sum may be an integer or float.

Syntax

array_sum($array)

Parameters

$array: It is an array whose sum needs to be calculated.

Return value

It returns the sum obtained after adding all the elements together.

Visual RepresentationVisual Representation of PHP array_sum() Function

Example 1: How to Use array_sum() function

<?php

$arr = [11, 22, 33, 44];

print_r(array_sum($arr));

Output

110

In this example, array_sum() calculates the sum of the values in the $arr array, which is 110.

Example 2: Using Associative ArrayVisual Representation of Using Associative Array

<?php

$arr = ["Rohit" => 88, "Gill" => 92, "Virat" => 77, "Rahul" => 43]; 

print_r(array_sum($arr));

Output

300

Example 3: Passing an empty arrayVisual Representation of Passing an empty array

 

<?php

$arr = [];

print_r(array_sum($arr));

Output

0

Example 4: Using array_sum() function to calculate the average

If you want to find an AVERAGE of the values in an array, use the sum and count the functions together.

<?php

$arr = [11, 22, 33, 44];

$average = array_sum($arr) / count($arr);

print_r($average);

Output

27.5

Example 5: Integers and String Values in array_sum()

If you pass the array containing both the strings and integers, the array_sum() Function returns a sum of integers. The strings are considered as 0.

<?php

$arr = ['krunal', 21, 'ankit', 19];

echo array_sum($arr);

Output

40

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.