Random seeds with PHP

Ever wondered how to display random information within a web page? 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.

Definitions

srand – Seed the random number generator
array – An ordered map. An array maps values to keys

Example

Here 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 srand

The 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 web page:

<?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.