Random Quote Script in PHP
There are many random quote scripts out there, but not all are created equal. This morning I decided I wanted to create a random quote generator for my own amusement. Specifically, I wanted a page that would return a random proverb from Puddn’head Wilson’s Calendar of Mark Twain’s The Tragedy of Puddn’head Wilson. A quick Google search seemed to indicate there was no single place to retrieve these quotes. I decided to place all of the quotes in a single text file and place a pound sign (#) between each of them as a delimeter.
For example:
Whoever has lived long enough to find out what life is, knows how deep a debt of gratitude we owe to Adam, the first great benefactor of our race. He brought death into the world. - Pudd'nhead Wilson's Calendar # Adam and Eve had many advantages, but the principal one was, that they escaped teething. - Pudd'nhead Wilson's Calendar # ...
Most random quote scripts have you manually create an array of strings. Such as:
$quotes[] = "This is a quote"; $quotes[] = "This is another";
But, this is extremely inefficient from an end user perspective. And it’s not easy to add quotes. Instead, I chose to read in the file as one string and split it up based on my chosen delimeter (#).
The resulting code ended up being very simple:
$quote_repository = "wilson.txt"; $quotes_raw = file_get_contents($quote_repository); $quotes = split("#",$quotes_raw); srand ((double) microtime() * 1000000); $r = rand(0,count($quotes)-1); echo "<p>".$quotes[$r]."</p>";
To shortcut, the following would also be acceptable:
$quotes = split("#",file_get_contents("wilson.txt")); srand ((double) microtime() * 1000000); $r = rand(0,count($quotes)-1); echo "<p>".$quotes[$r]."</p>";
And that’s all there is to it. It pulls in all of the quotes, splits them into arrays, and displays a random one each time the script is loaded. It’s elegant and extensible. Click here for a random Puddn’head Wilson quote.
