Search code examples
phparraysaddition

Problem with addition of array values in PHP


I have some data in an array of objects, and I need to sum the values stored in $data['gross'].

$data = [
 [
 "title" => "The World's End",
 "genre" => "Sci-fi",
 "year" => 2013,
 "gross" => 26004851
 ],
 [
 "title" => "Scott Pilgrim vs. the World",
 "genre" => "Sadness",
 "year" => 2010,
 "gross" => 31524275
 ]
];

I tried this with a loop:

for ($i = 0; $i <= (count($data)-1); $i++) {

   foreach ($data[$i] as $id => $row) {

      $sum = 0;     
 
      if ($id == "gross") {

         $sum += $row;
      }

      echo $sum;

   }

}

but instead of adding them, the numbers are concatenated as strings. Why? I tried to echo the type of this variable, but it's always an integer. Where is the problem please?


Solution

  • You can achieve it with one line of code:

    $data = [
     [
     "title" => "The World's End",
     "genre" => "Sci-fi",
     "year" => 2013,
     "gross" => 26004851
     ],
     [
     "title" => "Scott Pilgrim vs. the World",
     "genre" => "Sadness",
     "year" => 2010,
     "gross" => 31524275
     ]
    ];
    
    $sum = array_sum(array_column($data,'gross'));
    
    echo $sum;
    

    $sum will be 57529126 with this input