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
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..
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:
1
1/2 * P(1)
2/3 * P(2)
(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.
A generally good approach to this kind of situation is to:
file()
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)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With