faqts : Computers : Programming : Languages : PHP : Sample Code

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

61 of 76 people (80%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I display random content?

Jul 19th, 2004 23:37
Alder Rus, Philip Olson, Onno Benschop, Ilya Poropudas, rod men, http://www.directoryonclick.com , http://www.singapore-yellow-pages.com


Assuming we have a text file such as:
// quotes.txt
To be or not to be.
That is the question.
Is there anyone out there?
Let's open up this file using file() which as you read in the manual, 
will open the file as an array with each line being an element of that 
array.
  $lines = file('quotes.txt');
Before we use one of PHP's random functions, we first must plant a 
random seed.  Here's one way (there are many):
  mt_srand ((double) microtime() * 1000000);
Next, let's use mt_rand() to select a random line from our array of 
lines.  There are many ways to do this too, here is one.  We'll first 
get a random line number:
  $line_number = mt_rand(0,sizeof($lines)-1);
Now that we have a random number based on the number of lines in 
quotes.txt, let's put our code into a function:
  <?php
    $filename = 'quotes.txt';
    print getRandomLine($filename);
    function getRandomLine($filename) 
    {
    global $errors;
      if (file_exists($filename)) {
        mt_srand ((double) microtime() * 1000000);
        $lines = file($filename);
        $line_number = mt_rand(0,sizeof($lines)-1);
        return $lines[$line_number];
      } else {
        $errors['getRandomLine'][] = "File: $filename not found";
        return FALSE;
      }
    }
  ?>
Be sure to read the manual on mt_rand() mt_srand() rand() and srand().
  http://www.php.net/manual/en/function.mt-rand.php
Putting information out of a database can be done differently.  For 
example, the SQL language has a RAND() function.  In MySQL we can 
write 
that as follows:
  $sql    = "SELECT quote FROM tablename ORDER BY RAND() LIMIT 1";
  $result = mysql_query($sql);
  $line   = mysql_result($result,0);