Random array element

Returns a random element of a given array.

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] : '';
}
Snippet Details



// works with both array types:
$array = array(1,2,3);
 
// and also:
$array = array('one' => 1, 'two' => 2, 'three' => 3);
 
// example:
print random_array_element($array);

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

78945612301234567890qwertyuiopasdfghjklzxcvbnm May 21, 2010 at 04:40
/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().