Search code examples
phparrayscountsumarray-sum

Array sum and count row in PHP


I have a function getData that returns:

    array:4 [▼
  0 => array:1 [▼
    0 => "5689.01"
  ]
  1 => array:1 [▼
    0 => "5689.01"

  ]
  2 => array:1 [▼
    0 => "0.0"
  ]
  3 => array:1 [▼
    0 => "5665.11"
   ]
]

I need to COUNT number of rows (this time 4, as above) with values that are returned every time when I trigger a call and return total SUM of all results as listed.

 $rows = $this->get('app')->getData();

 if($rows) {
        foreach ($rows as $row) {
            $sumOfAll = 0;
            $total = count($rows);
            $sumOfAll += array_sum(array($row[0] * $total));

            dump($sumOfAll);die;
    }
}

I always get a wrong sum, in this case it was 22756.04.


Solution

  • Use array_sum and array_column to get the values and sum them.
    Then use count() to get the count.

    $sum = array_sum(array_column($arr, 0));
    $count = count($arr);
    
    echo "count is ". $count . " And sum is " . $sum;
    

    https://3v4l.org/HFbgc