Last active
December 20, 2015 08:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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