2.13 Generating Random Numbers
TechniqueUse PHP's mt_rand() function to generate a random number: <?php $rand_num = mt_rand(); ?> CommentsThe previous code would generate a random number with between 0 and an upper boundary that depends on the algorithm. The upper boundary can be retrieved with the mt_getrandmax() function. If you want, however, you can specify minimum and maximum values. <?php // Random number between 12 & 29 (inclusive) $rand_num = mt_rand (12, 29); ?> This is helpful if you are accessing items in an array randomly . Just generate a random number within the range of the array: <?php $rand_num = mt_rand (0, count ($ar) - 1); ?> $rand_num would then be an element in the array between 0 n -1, where n is the number of elements in the array. (We subtract 1 from the number of elements because arrays are indexed starting with 0.) If the mt_rand() function is not generating different random numbers, make sure to seed the random number generator before you generate the random number: <?php mt_srand ((double)microtime() * 1000000); $num1 = mt_rand(); $num2 = mt_rand(); ?> Computers, unlike humans , cannot generate a truly random number ”it is against the nature of the computer's engineering. Computers generate a pseudorandom number that is evenly distributed between a specified range of values. The number is generated using a complex mathematical formula, meaning that if the formula is given the same starting point (seed), it consistently generates the same number. The mt_srand() function sets a new seed based on the number that we give it. Therefore, we give it a constantly changing and large number ( microtime() * 1000000 ), typecast to a double. Note In PHP 4.1 the seeding of the random number generator is already done for you. Only use the [mt_] srand functions if you need to seed the generator with a specific seed. Gotcha Calling the mt_srand() function over and over is useless; it does not make your program generate a more random number. |