News Tutorials Projects Reviews Authors Contact Search Links Admin
 

Random Quotes : The Code

Random quotes for your website, a new interesting bit of dynamic content which changes with every refresh of the page. This is great because it makes your site more attractive, and encourages people to revisit your site.

There are many ways to do such a script, I'm going to do a basic one that works just by inserting code onto a page. Its quite straight forward. I don't have any decent quotes for my example, so I made some random sentances instead.

To begin, set up a set of simarly named sequentially numbered quotes.

<?php
$quote1 = "Happy bunnies jump around.";
$quote2 = "Lazy sand dunes and cool salty air.";
$quote3 = "Sludgey bogs in pea soup mist.";
$quote4 = "Calm wavy grass under violet trees.";
$quote5 = "Slick oily pumps in gritty dessert sands.";
?>

This defines the data we want to use/display.

Next, pick a random number, between 1 and 5.

<?php
$random_number = rand(1,5);
?>

Next, echo a random quote.

<?php
echo ${'quote'.$random_number};
?>

Note the special ${$variable} set up. This is a a 'variable variable'. Its like a pointer to another variable name, made out of string values.

My full code looks like:
<?php
$quote1 = "Happy bunnies jump around.";
$quote2 = "Lazy sand dunes and cool salty air.";
$quote3 = "Sludgey bogs in pea soup mist.";
$quote4 = "Calm wavy grass under violet trees.";
$quote5 = "Slick oily pumps in gritty dessert sands.";

$random_number = rand(1,5);

echo ${'quote'.$random_number};
?>

Give it a go. Put the code in a HTML file somewhere, save the file as quote.php, and load to any PHP enabled server.

 


Author: Markavian
Last edited on: 13th Mar, 1:22 pm
Please rate this article.

tutorial Pages