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:
60The 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:
4Summing 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