|
Webdesign articles: Random seeds with PHP |
Sample Web DesignsUser submitted Webdesign Articles and TutorialsRandom seeds with PHPBy James Middleton - 12th of April 2007 Ever wondered how to display random information within a webpage? Here are a number of things that you may want to try out. I have simplified the code as much as possible and (for the sake of the beginners) avoided using code optimising techniques - so apologies to the purist for the crudity of my scripts. Definitionssrand - Seed the random number generator array - An ordered map. An array maps values to keys ExampleHere are a number of suggested uses for the srand generator In the following example a random value will be taken from an array of values using the srand generator and then echoed out during page load. <?php srand (); $random = array("Blue", "Red", "Green", "Orange", "Cyan"); $random = $random[rand(0,count($random)-1)]; echo "The colour is $random now!"; ?> Going further with srandThe data that resides in the array can also be used for a vast host of tasks. For instance, you might want to randomise the colour of text for a webpage: <?php srand (); $random = array("Blue", "Red", "Green", "Orange", "Cyan"); $random = $random[rand(0,count($random)-1)]; ?> <body style="color:<?php echo $random ?>"> The colour of this text is <?php echo $random ?> </body> As you can see in the above example, the value of the $random string is echoed into the colour value for an inline style. Here is another useful example for srand<?php srand (); $random = array("file1.php", "file1.php", "file1.php", "file1.php", "file1.php"); $random = $random[rand(0,count($random)-1)]; include("/inc/$random"); ?> Now in the above example, I have substituted the name of a file with a random value from my array. The random file will now load it's contents into my page. Very useful for random articles, gallery pictures or page layouts. In fact, you could use this technique to random load just about anything into your design. About this ArticleAuthor: James Middleton You are free to use this article on your own website or email newsletters on the condition that you do not change it in anyway. You must also acknowledge the author and leave a link to: www.turningturnip.co.uk/web-design-articles/ Main SiteHome »Contact us» Articles & TutorialsPhotoshop Tutorials »Photoshop Articles » Webdesign Articles » Website Validation » SEO Facts » Content Management » Low Cost Hosting » Other PagesDisclaimer »Privacy Policy » |