18.10. Picking a Random Line from a File
Problem
You want to pick a line at random from a file; for example, you want to display a selection from a file of sayings.
Solution
Use the pc_randomint( )
function shown in Example 18-3, which spreads the
selection odds evenly over all lines in a file.
Example 18-3. pc_randomint( )
function pc_randomint($max = 1) {
$m = 1000000;
return ((mt_rand(1,$m * $max)-1)/$m);
}Here’s an example that uses the
pc_randomint( ) function:
$line_number = 0;
$fh = fopen('sayings.txt','r') or die($php_errormsg);
while (! feof($fh)) {
if ($s = fgets($fh,1048576)) {
$line_number++;
if (pc_randomint($line_number) < 1) {
$line = $s;
}
}
}
fclose($fh) or die($php_errormsg);Discussion
The pc_randomint( ) function computes a
random decimal number between
and $max, including 0 but excluding
$max. As each line is read, a line counter is
incremented, and pc_randomint( ) generates a
random number between 0 and $line_number. If the
number is less than 1, the current line is selected as the randomly
chosen line. After all lines have been read, the last line that was
selected as the randomly chosen line is left in
$line.
This algorithm neatly ensures that each line in an
n line file has a
1/
n chance of being chosen
without having to store all n lines into memory.
See Also
Documentation on mt_rand( ) at http://www.php.net/mt-rand.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access