Random Numbers in PHP PHP

Closely tied to sorting and searching is the generation of random numbers. Often random numbers are used to put lists out of order. They offer the opportunity to create surprise. They allow you to squeeze more information onto a single page by choosing content randomly for each request. You see this every day on the Web in the form of quotes of the day, banner ads, and session identifiers.

There are two important qualities of truly random numbers: their distribution is uniform, and each successive value is independent of the previous value. To have a uniform distribution means that no value is generated more often than any other. The idea of independence is that, given a sequence of numbers returned by the generator, you should be unable to guess the next. Of course, we can't write an algorithm that really generates independent values. We have to have some formula, which by its nature is predictable.Yet, we can get pretty close using what is called a psuedorandom number generator.

These use simple mathematical expressions that return seemingly random numbers. You provide a starting input called a seed. The first call to the function uses this seed for input, and subsequent calls use the previous value. Keep in mind that a seed will begin the same sequence of output values any time it's used. One way to keep things seeming different is to use the number of seconds on the clock to seed the generators.

The standard C library offers the rand function for generating random numbers, and PHP wraps it in a function of the same name. You pass upper and lower limits and integers are returned. You can seed the generator with the srand function, or just let the system seed it for you with the current time. Unfortunately, the standard generator on some operating systems can be inadequate. Previously, I suggested implementing your own random number generator if you needed better random numbers; however, Pedro Melo added a new set of functions to PHP that use the Mersenne Twister algorithm.

It generates 100 random numbers between 1 and 100, using the mt_rand function. It then computes the average and the median. If the distribution of numbers is uniform, the average and median will be very close. The sample set is really small, hough, so you will see lots of variance as you rerun the script.

Getting Random Numbers