0

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?

jh314
  • 27,144
  • 16
  • 62
  • 82

1 Answers1

0

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";
Sasi Varunan
  • 2,806
  • 1
  • 23
  • 34
  • Did you get any error or no output at all? i got 0.19 to make it clear try `print $sum."\n";` – Sasi Varunan Mar 23 '15 at 15:05
  • Hey Sasi, thanks for your help.However Nothing is outputted. However when I remove the ! from: `if(!$csv[0])` the output is the whole list of numbers plus the total at the end. However all I only need is for the total sum at the end to be displayed,not the whole thing. – Jeevan Daniel Mahtani Mar 24 '15 at 02:12
  • If `if(!$csv[0])` is the issue then try my updated code, were you can echo array_sum out of while loop – Sasi Varunan Mar 24 '15 at 10:17