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.
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.