Search code examples
phparraysmultidimensional-arrayassociative-arrayarray-sum

How to sum all of associative values of a multidimensional array?


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.


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