php: Get Random Text

📅 February 3, 2016
img-php-randquoteHere is a simple but fun PHP code snippet that displays one of several text strings chosen at random to add an element of surprise to a page.

First of all, a working PHP server is required in order to process PHP scripts. This could be a virtual machine using VirtualBox, for example, or something else on any platform. This short tutorial assumes that you have one set up and working.




function getImage()
   # Declare a new array
   $arrQuote = array();
   # Define array. One quote per line.
   $arrQuote[0] = 'Every shaver';
   $arrQuote[1] = 'Now can snore';
   $arrQuote[2] = 'Six more minutes';
   $arrQuote[3] = 'Than Before';
   $arrQuote[4] = 'By using';
   $arrQuote[5] = 'Burma-Shave';
   # Return random quote
   return $arrQuote[array_rand($arrQuote)];
# Get image
echo '<h1>' . getImage() . '</h1>';


For fun, we are using a classic Burma-Shave quote (due to its witty humor). The entire quote is broken into six verses, and each verse is stored in its own array element. This is done inside a custom PHP fucntion called getQuote(). getQuote() returns one of these verses at random for display, so the entire quote will not appear. Refreshing the browser will show different verses at random.

The random generation is performed by calling the array_rand() PHP function, which picks one element by default.

If more quotes are desired, simply add more elements to the array. Keep all indices in numerical order for consistency even though the code will still operate if the indices are out of order.

While simple, the same principal can be expanded upon to display random taglines in a page header or to show random taunts for quizzes.


, ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: