Detect if a row read in by fgetcsv is the last row of the csv file with PHP 7.4

539 views Asked by At

Is it possible to detect in the following code example if the current row is the last row? Here is my code:

$file = \fopen('/path/to/file.csv', 'rb');
while (($row = \fgetcsv($file, 0, ';')) !== false) {
    // Detect if it is the last row
    $isLastRow = ?;

    // Do some stuff for all rows and pass if it is the last row
    $myService->handleRow($row, $isLastRow);
}

I already tried it with $isLastRow = feof($file);, but that was not working. Does anyone have any ideas on how to do this?

1

There are 1 answers

0
Nono On

I think I have found a solution after all, contrary to the comments. This seems to work:

$fileEndPosition = \filesize('/path/to/file.csv');
$file = \fopen('/path/to/file.csv', 'rb');
while (($row = \fgetcsv($file, 0, ';')) !== false) {
    // Detect current file pointer position
    $currentPosition = ftell($file); 

    // Detect if it is the last row
    $isLastRow = $currentPosition >= $fileEndPosition;

    // Do some stuff for all rows and pass if it is the last row
    $myService->handleRow($row, $isLastRow);
}