$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.
PHP Coding tips & tricks. Function & error explanation, coding style, how tos etc. Short notes posted directly from developer work environment.
PHP Coding Tips
Friday, August 17, 2012
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:
Subscribe to:
Post Comments (Atom)
salt likit
ReplyDeletesalt likit
dr mood likit
big boss likit
dl likit
dark likit
BLN