LearnWebDesignOnline.com is proudly hosted by Hostmonster.com

In this tutorial, I'll show you several ways of picking random numbers in PHP.
The most basic way of generating a random number is by using the PHP rand() function as in ...
echo rand();
This will give you a random integer from 0 to the maximum value of the integers based on your web server's operating system (typically 32768 or higher).
Typically you want an integer between an range. So it is more common to do ...
echo rand(3,10);
Which will print out a random number from 3 to 10 inclusively.
Often you want to randomly pick an element from an array of values. For example, suppose you have an array of ad ids and you want to randomly choose an ad. One way to do it is by ...
$adsArray = array(255,306,307);
$choosenAd = $adsArray[rand(0,count($adsArray)-1)];
echo "The choosen ad id is " . $choosenAd;
where count($adsArray) will return the number of element of the array.
However, there is an specialized PHP function called array_rand() that is specifically designed for picking random elements out of arrays. It is can be used like ...
$adsArray = array(255,306,307);
$rand_keys = array_rand($adsArray);
$choosenAd = $adsArray[$rand_keys];
echo "The choosen ad id is " . $choosenAd;
The first parameter is the array of ads and the second parameter is the number of random elements that you want to pick from it. Since it is optional, I have omitted it and it defaults to 1. When the second parameter is 1, it returns the array key and I feed that key to the original adsArray to key the array value.
The tricky part is that if the second parameter is greater than 1, then array_rand() returns an array of keys instead of the key. So you would have to do ...
$adsArray = array(255,306,307);
$rand_keys = array_rand($adsArray,2);
$choosenAd1 = $adsArray[$rand_keys[0]];
$choosenAd2 = $adsArray[$rand_keys[1]];
echo "The choosen ad id is " . $choosenAd1. "<br>";
echo "Another ad id is " . $choosenAd2 . "<br>";
Note how I had to index the $rand_keys with 0 and 1.
