2D Imaging / Animation
Adobe Photoshop Adobe Flash 3D Imaging / Animation
Autodesk Maya Cinema 4D Game Development Valve Hammer (Source) Web Adobe Dreamweaver AJAX HTML / CSS PHP Programming C++ Java Python
Create a random quote generator
Views: 304
Submitted by: AksumkA on 7-8-09 at 01:30 am
In: PHP
Keywords: php, array, count, random, quote
We are going to make a very simple random quote generator. Obviously you can repurpose this to do whatever else you want something random of.
To start this off we are going to make an array of some random quotes:
$quote[] = 'Never forget to Google first, ask later';
$quote[] = 'Never going to give you up, Never going to let you down';
$quote[] = 'Will that ever just die? I hope so';
$quote[] = 'I cant pull anymore quotes off the top of my head';


For this example, the array elements do not need to be numbered. But if they were, they would be 0,1,2,3. Top to bottom.

Now we are going to pick a random array element. To do this we first need to know how many elements are in the array to begin with.

// Counts how many elements are in the array
$quoteCount = count($quote) - 1


We are subtracting one since the first element in an array is always 0. If we did not subtract one, out of our array the random number generator could hit four. There is no element at position four in our array, the last element is three.

Now that we have the total number of array elements, we can pick out a random number. We can use anything between zero and three with the array above.

// Pick a random number between 0 and the count we got above.
$quoteRandom = rand(0, $quoteCount);


This will set the variable $quoteRandom to a value between zero and three. All that is left to do is echo the results:

// Display the selected random quote on the page
echo $quote[$quoteRandom];