Poll

Helpful?

Yes
0 (0%)
No (Post why)
0 (0%)

Total Members Voted: 0

Voting closed: December 30, 2007, 01:28:22 AM

Author Topic: Random Line from a file  (Read 3172 times)

Acecool

  • Regular Member
  • **
  • Posts: 73
  • Karma: +0/-0
    • View Profile
    • PHP programmers forum
Random Line from a file
« on: December 04, 2007, 08:47:26 PM »
http://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 Code: [Select]

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



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.

fitzgerf

  • New Member
  • *
  • Posts: 1
  • Karma: +0/-0
    • View Profile
Re: Random Line from a file
« Reply #1 on: January 12, 2008, 12:22:41 AM »
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