I have a 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?
I have a 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 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)
{
return $ran[mt_rand(0, count($ran) - 1)];
}
$rand = rand(1,4);
or, for arrays specifically:
$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
You get a random number out of an array as follows:
$randomValue = array_rand($rand,1);
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 = array_rand($ran, 1);
Here is a ready to use function :)
function get_random_value($array) {
return $array[rand(0, count($array) - 1];
}
Example :
$ran = array(1,2,3,4);
$randomElement = get_random_value($ran);
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.