Random array element

Returns a random element of a given array.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
01/08/2007

Updated:
01/08/2007

Tags:
,


function random_array_element(&$a){
 
    mt_srand((double)microtime()*1000000);  
 
    // get all array keys:
    $k = array_keys($a);
 
    // find a random array key:
    $r = mt_rand(0, count($k)-1);
    $rk = $k[$r];
 
    // return the random key (if exists):
    return isset($a[$rk]) ? $a[$rk] : '';
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

/rsfii-0plk9joikjhhikljhnnkjhmhn,.j
Smith-Investment April 05, 2009 at 08:51
Last line "return isset($a[$rk]) ? $a[$rk] : '';"
Is a useful code.
Julian May 25, 2008 at 17:47
Thanks!!
Miguel April 12, 2008 at 22:26
Exactly what I was looking for, thank you!
Donald April 04, 2008 at 22:56
Just use the built-in function array_rand().