Book HomePHP CookbookSearch this book

18.11. Picking a Random Line from a File

18.11.1. 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.

18.11.2. 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);

18.11.3. 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.

18.11.4. See Also

Documentation on mt_rand( ) at http://www.php.net/mt-rand.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.