TechniqueYou 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)]; ?> CommentsBoth 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> |