2
$arrays = collect([[0,1], [0,2], [0,3]]);

How to get the sum of array?

I tried the code below, but I got error.

 return array_map('array_sum', array_map(null, ...collect->toArray());

How to achieve this?

$arrays = [0,6];
3
  • How [0,5] is calculated? Commented Nov 5, 2018 at 11:26
  • 1
    How it is calculated? Explain the algorithm of summation. Commented Nov 5, 2018 at 11:34
  • 3
    1 + 2 + 3 = 6 . not 5 Commented Nov 5, 2018 at 11:41

2 Answers 2

5

sum each element keeping the key

    $arrays = collect([[0,1], [0,2], [0,3]]);
    $sum = array_fill(0, count($arrays->first()), 0);
    foreach ($arrays as $collection) {
        foreach ($collection as $key => $value) {
            $sum[$key] += $value;
        }
    }
    dd($sum);

this outputs

array:2 [▼
  0 => 0
  1 => 6
]
Sign up to request clarification or add additional context in comments.

Comments

1

Get sum using Collections in Laravel:

    $item1_sum = 0;
    $x = collect([[5,1], [0,2], [4,3]])
            ->sum(function($item) use (&$item1_sum) {
                $item1_sum += $item[1];
                return $item[0];
            });
    dd([$x, $item1_sum]); // [9, 6]

1 Comment

[0, 6] because 1 + 2 + 3 = 6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.