Posts

Showing posts with the label mt_rand

Get random element from an array in PHP

This tutorial will show you how to get a random element from an array in PHP. We will use mt_rand function and count to determine minimal and maximal index of a array. Remeber that arrays are indexed from 0, so if you have a ten elements array, the elements have indexes from 0 to 9. So, we need a random number that will by at least 0 but smaller than 10. Wi will user mt_rand function te generate that number. Se example how to use count and mt_rand to get random element from an array: $array = array( 1,2,3,4,5 ); echo $array[mt_rand(0,count($array)-1)]; As you can see we have to substract 1 from the size of an array. Also we use faster and better function mt_rand, because rand is slower and less randomness.

Why not to use rand() in PHP

The rand() function in PHP is much more older, and doesn't generate such a good results as mt_rand(). What means good ? Just random. Computers cannot create real random numbers, so rand() and mt_rand() are just using some mathematic calculations to create pseudo random numbers, and mt_rand() has better and faster algorithm. Code sample: $i = rand(1,5); // don't use ! $i = mt_rand(1,5); // better If you want to check this, just generate a image with black and white pixels, selecting it by rand and mt_rand 0 and 1 values. You can see some patter-like areas in image created by rand()