PHP Files Picking a Random Line from a File - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Files Picking a Random Line from a File - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, July 10, 2019

PHP Files Picking a Random Line from a File

PHP Files 



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

Spread the selection odds evenly over all lines in a file:

       $line_number = 0;

       $fh = fopen(__DIR__ . '/sayings.txt','r') or die($php_errormsg);
       while (! feof($fh)) {
              if ($s = fgets($fh)) {
                     $line_number++;
                     if (mt_rand(0, $line_number - 1) == 0) {
                            $line = $s;
                     }
              }
       }
       fclose($fh) or die($php_errormsg);

Discussion

As each line is read, a line counter is incremented, and this example generates a random integer between 0 and $line_number - 1. If the number is 0, 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.

No comments:

Post a Comment

Post Top Ad