6.21 Extracting a Random Line from a File


You want to take a random line from a file; an example of this might be those fortune -telling programs.

Technique

You can load a file into an array and then pick a random element of the array:

 <?php $f_contents = file ($fn); srand ((double)microtime()*1000000); $random_line = $f_contents[ rand (0, (count ($f_contents) - 1)) ]; ?> 

Or you can use the built-in array_rand() function to return the key for a random array element:

 <?php $f_contents = file ($fn); srand ((double)microtime()*1000000); $random_line = $f_contents[array_rand ($f_contents)]; ?> 

Comments

Both of these solutions use the same concept: reading a file into an array and picking a random element. array_rand() comes in handy when you want to pick several lines because you can call it with an extra argument that specifies how many random elements you want and array_rand() returns the keys for them in an array.

This solution is especially useful for programs such as the following fortune-telling program:

 <html> <head>      <title> Fortune Teller, Find out your fortune </title> </head> <body bgcolor="#ffffff" text="#000000" link="#0000FF" vlink="#FF00FF"  alink="#FF0000"> <h1>YOUR FORTUNE IS:</h1> <?php srand ((double)microtime()*1000000); $f_contents = file ("/usr/home/sterling/fortunes.txt"); $line = $f_contents[array_rand ($f_contents)]; print $line; ?> <br><br> <a href="<?php echo $PHP_SELF; ?>">Get your fortune again</a> </body> </html> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net