Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to sum the values of an array

Short answer

array_sum() adds up all the values:

<?php
 
echo array_sum([10, 20, 30]);

Output:

60

The average

Divide the sum by count(). The check prevents division by zero for an empty array:

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

Output:

4

Summing a field

array_column() extracts one field from every record, after which the values can be summed:

<?php
 
$orders = [['total' => 100], ['total' => 250]];
 
echo array_sum(array_column($orders, 'total'));

Output:

350

Functions used in this recipe

  • array_sum — Returns the sum of the values in an array.
  • count — Returns the number of elements in an array.

Thanks for reading!

Donate to the site — we work hard for you.