method sum documentation in bbn\X

Returns the sum of all values of the given field in the given array

Using an optional where condition to filter the result.

Example

$arr = [ ['age' => 19, 'first_name' => 'John', 'last_name' => 'Doe'], ['age' => 11, 'first_name' => 'Andrew', 'last_name' => 'Williams'], ['age' => 25, 'first_name' => 'Albert', 'last_name' => 'Taylor'], ['age' => 36.5, 'first_name' => 'Mike', 'last_name' => 'Smith'], ['age' => 33, 'first_name' => 'Andrew', 'last_name' => 'Smith'], ]; X::sum($arr, 'age'); // (float) 19 + 11 + 25 + 36.5 + 33 X::sum($arr, 'age', ['first_name' => 'Andrew']); // (float) 11 + 33 X::sum($arr, 'age', function ($item) { return $item['first_name'] === 'John' || $item['first_name'] === 'Mike'; }); // (float) 19 + 36.5 function(array $ar, string $field, $where = NULL) { $tot = 0; if ($res = $where ? self::filter($ar, $where) : $ar) { foreach ($res as $r) { $r = (array)$r; $tot += (float)($r[$field]); } } return $tot; }

Returns the sum of all values of the given field in the given array BBN is a suite of PHP and JS libraries and VueJS components - all open-source! bbn.io, build applications, the quick way

This website uses cookies to ensure you get the best experience on our website.