How to get random value out of an array? How to get random value out of an array? arrays arrays

How to get random value out of an array?


You can also do just:

$k = array_rand($array);$v = $array[$k];

This is the way to do it when you have an associative array.


PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php

$ran = array(1,2,3,4);$randomElement = $ran[array_rand($ran, 1)];


You can use mt_rand()

$random = $ran[mt_rand(0, count($ran) - 1)];

This comes in handy as a function as well if you need the value

function random_value($array, $default=null){    $k = mt_rand(0, count($array) - 1);    return isset($array[$k])? $array[$k]: $default;}