Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_sum

Returns the sum of the values in an array.

Available since: PHP 4

Syntax

array_sum(array $array): int|float

Parameters

ParameterTypeDescription
$arrayarrayAn array of numbers.

Return value

int|floatThe sum of the elements; 0 for an empty array.

Examples

Sum of integers and of floats:

<?php
 
echo array_sum([1, 2, 3]), "\n";
echo array_sum([0.5, 1.25]);

Output:

6
1.75

The arithmetic mean:

<?php
 
$marks = [4, 5, 3, 5];
 
echo array_sum($marks) / count($marks);

Output:

4.25

Notes

Before computing an average make sure the array is not empty, otherwise you divide by zero.

See also

  • count — Returns the number of elements in an array.
  • max — Returns the largest of the given values.

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.