Page 1 of 1

Generating a random number - is this code random enough?

Posted: Sat Oct 03, 2009 12:04 pm
by Ingenious
Hi everyone, this is my first post so be gentle :D

I'd like to ask for your opinions on something "random" (literally).

I need to generate a random whole number between 1 and x. The background to this is I am rotating images on my forum. I want these are numbered between 1 and x where x is the number of images which might change from time to time. These are banner adverts. Also in some sections I list all the images 1 to x but in a random order.

I'm not worried about tracking who has seen what, so don't need to use cookies or databases - and that's largely irrelevant here anyway. I just need on each page request to pick a random number or take the numbers 1 to x in a random and non-repeating order.

The code I am using, which works OK, is this:

Code: Select all

 
$ads=6;
// example here shuffles the numbers 1-6
$adverts=range(1,$ads);
shuffle($adverts);
$randomnumber=$adverts[0];
 
The reason why this is done using an array is on some pages I display ALL the images, just in a random order, eg, 4,2,3,1,5,6.

OK so my questions....

1. Would you agree the above way of getting the numbers 1-x in a random order in an array is very good? Is it random enough or is there a better way?

2. To generate just ONE whole number between 1 and x, I don't really need to use an array as per above - is there a quick and reliable - and random - way of generating an integer between 1 and x?

Thanks in advance for any tips.

Re: Generating a random number - is this code random enough?

Posted: Sat Oct 03, 2009 1:17 pm
by John Cartwright
It all depends on your "randomness requirements". If you want a simple "relatively" random solution, then mt_rand() should do fine. Otherwise, take a look at this user comment.

Re: Generating a random number - is this code random enough?

Posted: Mon Oct 05, 2009 5:04 am
by Ingenious
John thanks for taking the time to reply. I think mt_rand() as you suggest is a good way to get a single random, whole number :D