array_sum
Returns the sum of the values in an array.
Available since: PHP 4
Syntax
array_sum(array $array): int|floatParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | An 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.75The arithmetic mean:
<?php
$marks = [4, 5, 3, 5];
echo array_sum($marks) / count($marks);Output:
4.25Notes
Before computing an average make sure the array is not empty, otherwise you divide by zero.
See also
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.