forgodsakehold
forgodsakehold

Reputation: 904

fgetcsv not returning data from csv file

// file opened with open before this
while ($dt = fgetcsv($dfp) !== FALSE) {
    $csvrows[] = $dt;
}

If I dump $csvrows, I get an array of bools each being TRUE. If I dump $dt within the loop, $dt = TRUE.

But this works:

// file opened with open before this
while ($dt = fgetcsv($dfp) !== FALSE) {
    $csvrows[] = fgetcsv($dfp);
}

I get the data from my CSV file nicely populated into $csvrows (but I am missing rows of data, because fgetcsv($dfp) is also called in the evaluation statement of the loop.

How come, and how do I solve to get all the data in my CSV file?

The PHP documentation says that what fgetcsv returns is an array of data, not a bool.

Upvotes: 0

Views: 649

Answers (1)

Don't Panic
Don't Panic

Reputation: 41810

This is an operator precedence issue. You can add some parentheses to specify the correct grouping.

while (($dt = fgetcsv($dfp)) !== FALSE) {

Changing the order in the expression should also work.

while (false !== $dt = fgetcsv($dfp)) {

As it's currently written, you're assigning the result of fgetcsv($dfp) !== FALSE to $dt, because comparison has a higher precedence than assignment.

Upvotes: 2

Related Questions