Quickly and Efficiently Counting CSV Rows with PHP

February 28th, 2025 • 2 minutes read time

Here's a fast, easy way to count the number of rows in a CSV with PHP, even if it has millions of rows.

There are a few methods for reading the row count of CSV files in PHP. For a recent course I created here on Codecourse, I needed a solution to work with hundreds of thousands (or millions) of rows.

Here's the entire snippet — I'll explain how this works below.

$file = new SplFileObject('transactions.csv', 'r');
$file->seek(PHP_INT_MAX);

$rows = $file->key() + 1; // the row count

Assuming transactions.csv contains 12 rows, $rows will equal 12!

So, how does this work?

First, we use SplFileObject to read a CSV file without loading the entire thing into memory. We'd see increased memory usage if we used another method of reading a file like file_get_contents and the CSV file was huge.

$file = new SplFileObject('transactions.csv', 'r');

Next up, because we're reading this file but don't have access to its entire content, we use seek to seek a specified line in the CSV. Because we don't know how many lines there are, we use PHP_INT_MAX since that's the max we'll be allowed to seek anyway.

$file->seek(PHP_INT_MAX);

Finally, as we've 'seeked' to the max possible row in the CSV, we use key to fetch the position. Since this is zero-indexed, we add 1.

$rows = $file->key() + 1;

If you know the CSV you're reading has a header, you can skip incrementing it.

So, there's a short and memory efficient way of reading and counting rows in a CSV file in PHP!

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under