Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo random line from text file

Tags:

file

php

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

like image 475
Sahil Pasricha Avatar asked Nov 27 '22 21:11

Sahil Pasricha


2 Answers

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.

like image 134
Mohamed Nuur Avatar answered Dec 06 '22 09:12

Mohamed Nuur


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)];
like image 33
John Conde Avatar answered Dec 06 '22 09:12

John Conde