Home > database >  Loop and sum array Laravel 8
Loop and sum array Laravel 8

Time:02-02

does anyone know how to loop an array & sum it? So i have an array with 3 values like in the picture below

enter image description here

and this is my code

enter image description here

CodePudding user response:

use laravel collection sum() method instead of getting sum of array value in loop

collect([1, 2, 3])->sum();

or use php array_sum() method

array_sum([1, 2, 3, 4, 5]);

CodePudding user response:

Use php method array_reduce().

array_reduce([1,2,3], function($a, $b) { return $a   $b; }, 0);
// output 6

document: https://www.php.net/manual/en/function.array-reduce.php

  • Related