There are several ways to successfully sum the values:
Using: $array = [['user1' => 20], ['user2' => 30], 3 => ['user3' => 10]];
(Demo of all approaches)
A purely function-base approach:
// reindex subarrays, isolate zero column, sum values
echo array_reduce(
$array,
fn($result, $row) => $result + current($row),
0
);
A recursive approach (concise, but arguably "overkill"):
// visit each leafnode, increase the $sum ("modifiable" via &) tally
array_walk_recursive(
$array,
function($v) use(&$sum) {
$sum += $v;
}
);
echo $sum;
A language construct approach (purely foreach loops):
$total = 0; // without this declaration, you will generate: "Notice: Undefined variable"
foreach ($array as $subarray) { // iterate outer array
foreach ($subarray as $v) { // iterate each inner array
$total += $v; // increase $total
}
}
echo $total;
All solutions above will output 60
.
p.s. Assuming you have unique user identifiers in each subarray, you can merge the subarrays with the "splat operator" to produce a 1-dimensional array and that will set up the use of array_sum()
. I strongly recommend this one. (Demo)
echo array_sum(array_merge(...$array));
// 60