Jump to content
Larry Ullman's Book Forums

Recommended Posts

I have a question, inspired by the "Random Quotes" mini-application, used as an example of writing to a file and reading from a file, in Chapter 11 of this book.


The "read from file" part of this application picks a random quote from an array, and outputs it to a web browser.


I want to figure out the simplest way to improve this script, so that the random quotes that it outputs are not repeated, as long as there are quotes left in the file.


For example, the script has output the array element # 0. I want it to remember that the element # 0 has been output, and the next time to output any other element of the array, but not 0 - and so on, until the script runs out of quotes, in which case it can start over again.


I'm not asking this for any important or practical reason, but I'm just curious, if a simple an elegant solution could be found.


Would appreciate a creative suggestion!

Link to comment
Share on other sites

There are any number of approaches, but perhaps the simplest would be to store the array of quotes in a cookie array.

By doing so, you only have to load the quotes from the file once, and from there, you could modify (i.e., delete quotes from) the cookie array as you please without effecting the original text file.


The following is a simple example using some PHP code (which I will not swear by because I'm at work and cannot test the code right now):


 if (!isset($_COOKIE['quotes'])) { // Only get the quotes from the file if they're not already in a cookie.

   $data = file_get_contents('quotes.txt');

   $quotes = explode("\r\n", $data); // May have to change the delimiter.

   foreach ($quotes as $k => $v) {

  setcookie("quotes[$k]", $v, 60 * 60 * 24 * 180 + time()); // Set to expire in about 6 months.



 $rand_quote = floor(rand() * count($_COOKIE['quotes']));

 echo $_COOKIE['quotes'][$rand_quote]; // Print a random quote.

 array_splice($_COOKIE['quotes'], $rand_quote, 1); // Remove the used quote.

 if (count($_COOKIE['quotes']) === 0) { // If the quotes array is empty, unset.




Lemme know if that's what you wanted.

  • Upvote 1
Link to comment
Share on other sites


  • Create New...