Random Line from a file

http://www.acecoolco.com/tutorials/18/random-line-from-a-file/page_1/tutorial_27.html

This tutorial will show you how to retrieve a random line from a file which can be used for random quotes, random ads and other misc purposes

Code pasted for ease of use:

Lets get started!

First, here is the completed code.
PHP Code Box

[php]

<?php $file = file('file.txt'); $rand_line = rand(0, sizeof($file) - 1); $line = $file[$rand_line]; echo $line; ?>

[/php]

Now, we will break it down.

The file() function in php opens a file with each line as an array.
Next, we use rand(START, END) to generate a random number which will be used later to open a random line.
Next, with $file[$rand_line] we call the file, which was stored in an array, and open open the value at the random line key.
All we do next is echo it.

Thanks for that info, but can you take it a little further? Say one needs to iterate all the lines of a file or mysql table before repeating any. The rand() function is great, but cannot guarantee that the same line will not appear before all lines have appeared. How could one do this> :D

Sponsor our Newsletter | Privacy Policy | Terms of Service