Skip to content

Instantly share code, notes, and snippets.

@gooh
Last active December 20, 2015 08:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gooh/6098387 to your computer and use it in GitHub Desktop.
Save gooh/6098387 to your computer and use it in GitHub Desktop.
Retrieve the lines in a file in random order without repeating the lines or loading the file into memory first.
function getLinesInRandomOrder($filePath)
{
$file = new SplFileObject($filePath);
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY);
$file->seek(PHP_INT_MAX);
$linesToTry = range(0, $file->key());
shuffle($linesToTry);
foreach ($linesToTry as $line) {
$file->seek($line);
yield $file->current();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment