How to get random value out of an array?
I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
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;
}
$value = $array[array_rand($array)];
You could use the array_rand function to select a random key from your array like below.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];
or you could use the rand and count functions to select a random index.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];