Web Development

Generate Random Quotes with PHP

Generate Random Quotes with PHP

The following will show you how to generate simple random quotes using PHP.

The first step it to open the PHP script:

<?

Next we will need to open the array sequence.

$quote = array(

You can have as many as you want, just open each one as a new number:

1  => "a",
2  => "b",
3  => "c",
4  => "d",
5  => "e",

Now close the array:

);

Now set up the random sequence. Notice that rand (1,5) meaning 1 through 5. you could change this to be 3,5 and it would only use array 3, 4 and 5:

srand ((double) microtime() * 1000000);
  $randnum = rand(1,5);

Notice that the array uses $quote, and the random sequence uses $randnum, so we need to bind those two together:

echo”$quote[$randnum]“;

Now end the PHP script:

?>

Here is the complete code:

<?
$quote = array(
1  => "a",
2  => "b",
3  => "c",
4  => "d",
5  => "e",
);
srand ((double) microtime() * 1000000);
  $randnum = rand(1,5);
echo"$quote[$randnum]";
?>

About the author

Written by Darren W..

Darren Hedlund is a freelance Web developer, writer, and data analyst. Darren has a degree in Computer Information Science and has spent the last 15 years developing application and environments from hand held, windows, web, virtual science, gaming, artificial intelligence and graphics design.

Darren's coding knowledge ranges from C+, Visual Basic, .NET, PHP, JSP, REXX, KIXX, and many others. His graphical and environmental knowledge stems in Macromedia Flash, 3D studio Max, Curious Labs Poser, Adobe Photoshop, and many others. Darren works in many platforms ranging from database, visual design, and, system development.

If you found this post useful you may also want to check these out:

  1. Creating a Drop Down Selection with an Array
  2. Using Variable Referencing
  3. Do Not Reassign the Object Reference of a Locked Object
  4. Conduct Web experiments using PHP, Part 1
  5. JavaScript Tutorial Part I- Some Basics
  6. The PHP Explode Function, Split a String by String