Welcome to Server Circle. It's a friendly site and all levels of experience are welcome. Be aware that we use cookies for your login.
Server Circle - Ask questions about Servers and get answers from experts.
Beta (1.00 sec)
Pulling a random line from a text file in PHP

Any PHP experts able to put a quick function together for pulling a random line from a text file ?

Thanks very much.
Asked by:
BonoEstente
1464 points
 Report Abuse
 Share Page - Category: Programming - Tags: Pulling a random line from a text file in PHP
 Enter your response
Please use Pastie.org to paste lengthy code or to fix formatting issues with code
  • Responses in reverse (1)

Here's a snippet that should do that without loading the whole file into memory at once.



<?php

$h=fopen("filename.txt",'r');

while($line=fgets($h)){

if(rand(0,$i++) < 1){$output = $line;}

}

fclose($h);

echo $output;

?>


Response by:
jercos
29 points


  • Related Questions
About Us : Contact Us : Etiquette : Terms : CDN Failover : ShorterURL : CDN Fallback : © 2013 Server Circle