How can I get the total number of rows in a CSV file with PHP?

How can I get the total number of rows in a CSV file with PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Your Row Counter Might Be Off and How to Fix It

The logic in your snippet relies on fgetcsv() returning false when it hits the end of the file. In theory, this is sound. However, the specific failure mode you are likely encountering stems from how the loop variable $row is initialized. If that variable exists but has not been explicitly set to zero before the loop starts, PHP will treat it as null, which evaluates to false. While a boolean check inside the loop works, simply echoing the variable after the loop often yields 0 if the initialization was missed or if the file is empty.

To get an accurate count of total rows in a CSV file using PHP, you need to ensure the counter starts at zero and handle the file pointer correctly. The most robust pattern looks like this:

$filename = 'test.csv';
$rowCount = 0;

if (($fp = fopen($filename, 'r')) !== FALSE) {
    while (($record = fgetcsv($fp)) !== FALSE) {
        $rowCount++;
    }
    fclose($fp); // Always close the resource after reading

    echo $rowCount;
} else {
    // Handle file not found or permission errors
    echo "Error opening file: " . $filename;
}

The critical line here is $rowCount = 0;. Without it, you are relying on implicit initialization which can lead to unpredictable results depending on the execution context. Additionally, remember to close the file handle with fclose() once reading is complete. Leaving a file open unnecessarily consumes system resources and can cause issues in long-running scripts or when processing multiple files sequentially.

Performance Considerations for Large Files

While the method above is perfectly fine for small to medium-sized datasets, iterating through a file line-by-line using fgetcsv() becomes a bottleneck when dealing with massive CSVs containing millions of rows. The overhead of parsing every single row in PHP adds up significantly compared to native system tools.

If performance becomes a concern, the standard Unix utility wc is often the preferred approach. It calculates the number of lines directly from the filesystem without loading data into memory. You can invoke it via a shell command from PHP:

$filename = 'test.csv';

if (file_exists($filename)) {
    $count = shell_exec("wc -l < {$filename}");
    
    // wc outputs "number filename", so we need to extract just the number
    if ($count) {
        $rowCount = trim(explode(' ', $count)[0]);
        echo $rowCount;
    }
}

This approach is significantly faster because it offloads the counting logic to the operating system. However, you must be aware of a specific edge case: wc -l counts newline characters, not necessarily rows. If your CSV file lacks a final newline character at the end of the last line, wc -l will undercount by one. For example, if a file has 5 data lines but no trailing newline, wc -l might report 4.

To mitigate this risk while keeping the speed benefit, you can verify the content of the last byte or add an artificial newline before counting, though that modifies the file logic which may not always be desirable. A safer middle ground for large files is to use PHP's built-in stream statistics if available, or stick to the fgetcsv loop but run it in a dedicated child process (like via pcntl_fork) so the main application doesn't hang while parsing millions of lines.

The LaravelCompany Context

If you are building this functionality within a larger web application stack, particularly one utilizing the Laravel framework, consistency in how you handle file processing is key. While raw PHP functions like fgetcsv give you granular control, frameworks often provide higher-level abstractions for handling data imports and exports. Resources like https://laravelcompany.com discuss various strategies for managing file uploads and CSV parsing within the ecosystem, including leveraging packages that can chunk large files to prevent memory exhaustion.

When choosing between a raw loop and a third-party package, weigh the complexity against your specific needs. A simple row count is rarely worth the overhead of a heavy library unless you are also transforming or validating the data simultaneously. Stick to the simplest solution that solves the problem: initialize your counter, read until false, and close the handle.

Our network