Entry
How can I read a line at random from a file?
Jun 29th, 1999 23:52
Nathan Wallace, Fred Isler, Colin Viebrock, Ariel
There are a few ways read a line from a file at random.
If you don't want to lond the file into memory, do it in two passes,
count the lines in the file (unix command wc is probably fastest for it,
popen it) then pick an random number, and find that line. You can use
head, or tail for it, or do it in php.
If you can load it into memory, then use file to get an array, count the
array, and pick an element. Here is some code to do this:
// get the number of lines in the file
$fileLines = file("file.txt");
$i = count($fileLines);
// seed and pick a random number between 0 and $i:
srand((double)microtime()*1000000);
$idx = rand(0,$i);
// print your random line:
print ("$fileLines[$idx]");