Generating a random number - is this code random enough?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ingenious
Forum Newbie
Posts: 2
Joined: Sat Oct 03, 2009 9:30 am

Generating a random number - is this code random enough?

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post 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.
Ingenious
Forum Newbie
Posts: 2
Joined: Sat Oct 03, 2009 9:30 am

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

Post 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
Post Reply