Reputation: 101
I've got the following 2d array and I want to sum all of the elements in each subarray.
Input:
$main_array = [
[1, 2, 3],
[2, 4, 5],
[8, 4, 3]
]
Desired Result:
[6, 11, 15]
I tried the following code:
foreach ($main_array as $key => $value)
$main_array[$key] = Array('1' => array_sum($value));
print_r($main_array);
But the array structure I got was:
Array
(
[0] => Array
(
[1] => 6
)
[1] => Array
(
[1] => 11
)
[2] => Array
(
[1] => 15
)
)
Upvotes: 3
Views: 3542
Reputation: 47900
Call array_sum()
on every row in your input array. array_map()
makes this operation expressive, concise, and doesn't require any new variables to be declared.
Code: (Demo)
$array = [
[1, 2, 3],
[2, 4, 5],
[8, 4, 3],
];
var_export(array_map('array_sum', $array));
Output:
array (
0 => 6,
1 => 11,
2 => 15,
)
Upvotes: 1
Reputation: 103135
Try this:
foreach ($main_array as $key => $value)
$main_array[$key] = array_sum($value);
That is, place the sum directly in the top level array.
Upvotes: 2
Reputation: 35136
When you're calling Array function you're explicitly making an array so you have to remove this from Array('1'=>array_sum($value));
This is how your code should look like
foreach ($main_array as $key => $value)
$main_array[$key] = array_sum($value);
Upvotes: 6