Question

I am having a problem with php fgetcsv() method. I can only get the value "1" instead of an array for each line. Here is the code:

$row = 0;
$teststring='';
$handle = fopen($savepath,'r');
if($handle!==FALSE){
    while(($data = fgetcsv($handle,2000,'|')!==FALSE)){        //I am using '|' as the delimiter
        echo (string)$data;
        if($row!=0){
            foreach($data as $d){
                array_push($result['added'],$d);
            }
        }
        $row++;
    }
    fclose($handle);
}

I tested a 3-line csv file and the result will be "111". Of course there is no value in array $result['added']. Could any body know what is going on? Thank you.

Was it helpful?

Solution

Order of operations!

while(($data = fgetcsv($handle,2000,'|')!==FALSE)){

PHP is interpreting this line as:

  • Call fgetcsv
  • Without casting, compare it to boolean false
  • Assign the result of this comparison to $data

This isn't what you want. Your parens are misplaced, you want the last one before the comparison:

while( ($data = fgetcsv($handle,2000,'|')) !== FALSE ){

I've added extra spaces to make the change more obvious.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top