4

My text file format is :

This is first line.
This is second line.
This is third line.

There could be more lines in the text file. How to echo one random line on each refresh from the text file with php. All comments are appreciated. Thanks

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Sahil Pasricha
  • 135
  • 1
  • 3
  • 10
  • while this may work for a small number of row, if you want a solution for many lines, consider using a database. –  Aug 25 '12 at 03:59

2 Answers2

17

How big of a file are we talking? the easy approach is to load the entire file into memory as string array and pick a random array index from 0 to N and show that line..

If the size of the file can get really big, then you'd have to implement some sort of streaming solution..

Streaming Solution Explained!

The following solution will yield a uniformly distributed random line from a relatively large file with an adjustable max line size per file.

<?php
function rand_line($fileName, $maxLineLength = 4096) {
    $handle = @fopen($fileName, "r");
    if ($handle) {
        $random_line = null;
        $line = null;
        $count = 0;
        while (($line = fgets($handle, $maxLineLength)) !== false) {
            $count++;
            // P(1/$count) probability of picking current line as random line
            if(rand() % $count == 0) {
              $random_line = $line;
            }
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
            fclose($handle);
            return null;
        } else {
            fclose($handle);
        }
        return $random_line;
    }
}

// usage
echo rand_line("myfile.txt");
?>

Let's say the file had 10 lines, the probability of picking line X is:

  • P(1) = 1
  • P(2) = 1/2 * P(1)
  • P(3) = 2/3 * P(2)
  • P(N) = (N-1)/N * P(N-1) = 1/N

Which will ultimately give us a uniformly distributed random line from a file of any size without actually reading the entire file into memory.

I hope it will help.

Community
  • 1
  • 1
Mohamed Nuur
  • 5,536
  • 6
  • 39
  • 55
9

A generally good approach to this kind of situation is to:

  1. Read the lines into an array using file()
  2. echo out a random array value using array_rand()


Your code could look something like this:

$lines = file('my_file.txt');

echo $lines[array_rand($lines)];
Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
John Conde
  • 217,595
  • 99
  • 455
  • 496