0

I have a csv file which has this type of rows CSV file

This file has 240 rows with above data and somehow it has 700+ empty rows.. when I use this code to check for rows

function fn_get_order_csv($file){

    $all_rows = array();
    
    if (($handle = fopen($file[0]['path'], "r")) !== FALSE) {
        
        $headers = fgetcsv($handle);
        
        if(!empty($headers)){
            foreach($headers as $key=>$value){
                $headers[$key] = str_replace( ':','_',preg_replace('!\s+!', '_',  strtolower( trim($value))) );
            }
        }
        while ($row = fgetcsv($handle)) {
            if(!empty($row)){
                $all_rows[] = array_combine($headers, $row);
            }
        }
    }
    
    return $all_rows;
}

In the above code the If(!empty($row)) still count empty row and return all 900+ rows But if I change it to If(!empty($row[4])) it return only 240 rows.... What am I missing to understand it correctly?

Rao DYC
  • 146
  • 11
  • Does this answer your question? [fgetcsv skip blank lines in file](https://stackoverflow.com/questions/18324369/fgetcsv-skip-blank-lines-in-file) – Worthwelle Dec 25 '21 at 02:16

1 Answers1

0

The empty function documentation states:

A variable is considered empty if it does not exist or if its value equals false.

Whereas the fgetcsv function documentation states:

A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.

An array containing a single null field is neither falsey, nor unset. Try using if($row === [null]) instead.

Worthwelle
  • 1,244
  • 1
  • 16
  • 19