How to get number of lines with SplFileObject?

The SplFileObject offers an itertor, one iteration per line:

$numberOfLines = iterator_count($file);

The function iterator_count is your friend here, doing the traversal for you and returning the number of iterations.

You can make use of the file object's SKIP_EMPTY flag to not count empty lines in that file.


iterator_count and line-by-line iterating using next() is broken in my php version 5.3.7 under Ubuntu.

Also seems broken fseek([any offset], SEEK_END) method. key() returns 0.

Iterate over large files using seek($lineCount) is too slow.

Simpliest 5.3.7-verified way is

// force to seek to last line, won't raise error
$file->seek($file->getSize());
$linesTotal = $file->key();

Counting 30000 lines requires now 0.00002 secs and costs about 20 kb of memory.

Iterations method takes about 3 seconds.


I agree with Николай Конев on using seek function is much faster than going through the entire file line by line, but as Twisted1919 said using the file size to seek the last line is confusing so my suggestion is use PHP_INT_MAX instead of the file size:

// force to seek to last line, won't raise error
$file->seek(PHP_INT_MAX);
$linesTotal = $file->key();

Tags:

Php

Spl