You want to pick a line at random from a file; for example, you want to display a selection from a file of sayings.
Use the pc_randomint( ) function shown in Example 23-26, which spreads the selection odds evenly over all lines in a file.
Finding a random line of a file
The pc_randomint( ) function computes a random decimal number between 0 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.
23.8.4. See Also
Documentation on mt_rand( ) at http://www.php.net/mt-rand.