Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

asadbekDev's avatar

Sum of array

$matrix = array( [1,2,3,4,5,6,8], [1,2,3,4,5,6,2], [1,2,3,4,5,6,1], [1,2,3,4,5,6,3] );

sum of array

[1,2,3,4,5,6,8], [2,3,4,5,6], [3,4,5] [4]

like sum this

0 likes
4 replies
bugsysha's avatar
$sum = collect($matrix)->flatten()->sum();
bugsysha's avatar

Or if you need them by "subarray" then:

$sums = collect($matrix)->map(fn(array $items): int => array_sum($items));
piljac1's avatar

Your question is rather vague. What exactly do you expect? Do you expect that your $matrix ends up with the content [1,2,3,4,5,6,8], [2,3,4,5,6], [3,4,5], [4] or are you looking for a single number which is the sum of an array of array?

If you're looking for a sum of all numbers in the subarrays, you can use this logic:

$sum = array_sum(array_merge(...$matrix));

Basically, you merge all your inner arrays into one and sum the content of the resulting array. Of course, that only works with automatically assigned/integer array keys (which is what you show in your example), not string keys, because they can collide during the merge (some data would be lost).

What would work with colliding string keys (using Laravel's Arr class):

$sum = array_sum(Arr::flatten($matrix));

Please or to participate in this conversation.