Skip to content

Instantly share code, notes, and snippets.

@tyx
Created September 6, 2013 08:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyx/6461136 to your computer and use it in GitHub Desktop.
Save tyx/6461136 to your computer and use it in GitHub Desktop.
Count lines number on big files
<?php
$file = new SplFileObject("mybigfile.csv");
// Store flags and position
$flags = $file->getFlags();
$current = $file->key();
// Prepare count by resetting flags as READ_CSV for example make the tricks very slow
$file->setFlags(null);
// Go to the larger INT we can as seek will not throw exception, errors, notice if we go beyond the bottom line
$file->seek(PHP_INT_MAX);
// We store the key position
// As key starts at 0, we add 1
$count = $file->key() + 1;
// We move to old position
// As seek method is longer with line number < to the max line number, it is better to count at the beginning of iteration
$file->seek($current);
// Re set flags
$file->setFlags($flags);
echo $count.PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment