0
votes

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?

1
Try casting to an int $sum += (int)$row; - omeanwell
@omeanwell still same problem - TheDareback
Every loop you set $sum = 0; so you will only get the last line. - Felippe Duarte
@FelippeDuarte well of course my fault. I've been looking into this for too long. well thank you - TheDareback

1 Answers

0
votes

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