Home > database >  How can i sum array elements as an array in laravel
How can i sum array elements as an array in laravel

Time:06-29

i have two arrays and i want to make calculations with the elements in these arrays.

$result1=DB::where('elements',$elements)->get();

$result2=DB::where('otherElements',$otherElements)->get();

for example; $result1 = [5,7,9] and $result2 = [0,5,9]

$result3 must be (for multiply) [0,35,81] or (for sum) [5,12,18]

i tried to do with for loop but it does not solve my problem in blade file.

so i want to do it in controller then send the result to the blade file.

CodePudding user response:

Also you can use array_map and array_sum as:

$result1 = [1, 2];
$result2 = [1, 2];

$result3 = array_map(function () {
    return array_sum(func_get_args());
}, $result1, $result2);

print_r($result3);

CodePudding user response:

You can use array_map same as :

$result3 = array_map(function($v1, $v2){
    return $v1   $v2;
}, $result1, $result2);

$result4 = array_map(function($v1, $v2){
    return $v1 * $v2;
}, $result1, $result2);

Code online in here

  • Related