Search code examples
phparrayscsvfgetcsv

sum row data in csv file using php


I am trying to sum a single row of data(numbers) from a csv file to display the total number using php. this is the csv file I have:

A

0.01
0.1
0.02
0.01
0.02
0.01
0.02

Basically it stretches on. A is basically the first row alphabet in excel.

Basically it stretches on. I am trying to sum up the row in PHP.

This is my code so far:

if (($handle = fopen("file.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   $data = array();

   echo array_sum($data);
  }
}

My output is basically : 000000000000000000000000000000000000000000000000000

I cant seem to figure out why? Could anyone assist me with this?


Solution

  • You could try like this

    <?php
    $file = fopen("file.csv","r");
    $sum = 0;
    while(!feof($file)) {
        $csv = fgetcsv($file,1024);
        if(!$csv[0]){
                print $sum."\n";
        }
        $sum = $sum + $csv[0];
    }
    

    or declare array before the while loop

    <?php
    $file = fopen("file.csv","r");
    $sum = array();
    while(!feof($file)) {
        $csv = fgetcsv($file,1024);
        array_push($sum,$csv[0]);
    }
    echo array_sum($sum)."\n";