-1

I want to fetch all the contents of a csv file into an array so I used the fgetcsv function. It is working correctly, but when I want to return my array it is empty. The problem seems to be outside the while loop.

Here is my code:

$filepath="Data\";
$csvfile=array();    /* here i did declaration */

$csvfile=csvcontain($filepath);
print_r($csvfile);  /*prints empty array */

function csvcontain($filepath)
{
    foreach (glob($filepath."*."."csv") as $filename) 
    {
        $file_handle = fopen($filename, 'r');
        while (!feof($file_handle)) 
        {
            $csv=fgetcsv($file_handle, 1024);
            $csvfile=$csv;
        }
    }
    fclose($file_handle);
    return $csvfile;
}

I am not getting where it is going wrong.

glomad
  • 5,539
  • 2
  • 24
  • 38
snehal
  • 429
  • 5
  • 11
  • 25
  • PHP does not have block scope, the variable is there perfectly fine. If it isn't, that means the loop has never been executed. – deceze Nov 05 '13 at 10:32
  • Close your file after opening it when you did all the read operations. You are just closing the last opened file here (put it inside foreach after the while loop) – Jonathan Muller Nov 05 '13 at 10:32
  • when i print in side while loop the data is coming in array.. – snehal Nov 05 '13 at 10:33
  • @Koren i did.but still it is empty. – snehal Nov 05 '13 at 10:38
  • The code you have there has a parse error. You need an extra \ before the closing single quote when filepath is declared. I am sure that this is not the issue, but it would help if you would edit to change that. – Belinda Nov 05 '13 at 10:41

1 Answers1

0

csvfile is being overwritten, not added to on each iteration of the loop.

Try replacing $csvfile=$csv; with $csvfile[]=$csv;. This should add a new element to an array.

Belinda
  • 1,230
  • 2
  • 14
  • 25