2

Why i am getting blank array at the end?

My PHP code :

$name = $_FILES["csv"]["tmp_name"];
$file = fopen($name,"r");

while(!feof($file)){

    $row = fgetcsv($file);

    $data = array(
        "1"     =>$row[0],
        "2"     =>$row[1],
        "3"     =>$row[2],
        "4"     =>$row[3]
    );

    echo "<pre>";
    print_r($data);
}
fclose($file);

And my result :

Array
(
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)

Array
(
    [1] => e
    [2] => f
    [3] => g
    [4] => h
)

Array
(
    [1] => 
    [2] => 
    [3] => 
    [4] => 
)

Abhishek Sharma
  • 6,689
  • 1
  • 14
  • 20
Sant Bohara
  • 33
  • 1
  • 6

2 Answers2

1

You can simply use "array_filter" function to remove blank array, Please find link with full code required: https://eval.in/640133

You just need to map and filter the result array to remove the empty array.

Thanks

Patrick R
  • 6,621
  • 1
  • 24
  • 27
0

Try Below code.If still it returns empty array at the end,that means your csv file may have blank space in one of the cell of last row.

 $name = $_FILES["csv"]["tmp_name"];

 $file = fopen($name,"r");

 while (($data = fgetcsv($file , 1000, ",")) !== FALSE) {

      echo "<pre>";

      print_r($data);

      echo "</pre>";

 }

 fclose($file);
Dinesh Belkare
  • 639
  • 8
  • 24
  • actually i want to assign CSV data to new array and push it into mysql.. above my code works fine, only the problem is blank array. – Sant Bohara Oct 20 '15 at 05:52
  • As you are sure about your csv file does not contain blank row,why can't you give try with this piece of code.If still you get blank array then I am sure there is blank row. – Dinesh Belkare Oct 20 '15 at 08:45
  • Thanks, it worked good. I reassigned it to new array and push to database. Thanks again. – Sant Bohara Oct 20 '15 at 09:36