Question

How do I sum all the values of this associative array:

Array ( 
    [0] => Array ( [user1] => 20 ) 
    [1] => Array ( [user2] => 30 ) 
    [3] => Array ( [user3] => 10 ) 
) 

Expected Output:

60

I tried, array_sum with no avail:

$lsd = Array ( [0] => Array ( [user1] => 20 ) [1] => Array ( [user2] => 30 ) [3] => Array ( [user3] => 10 ) ) 

print_r(array_sum($lsd))

I have been searching stackoverflow for past 2 hours without finding anything.

Was it helpful?

Solution

$array = Array ( 
 0 => Array ( "user1" => 20 ), 
 1 => Array ( "user2" => 30 ),
 3 => Array ( "user3" => 10 ) 
); 

$new=0;

foreach($array as $value){
 foreach($value as $value1){
  $new += $value1;
 }  
}
echo $new;

Output

60

OTHER TIPS

$lsd = array ( array ('user1' => 20 ), array ('user2' => 30 ), array ('user3' => 10 ));

$sum = array_reduce(
    $lsd,
    function($sum, $value) {
        $sum += array_pop($value);
        return $sum;
    },
    0
);

var_dump($sum);

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top