tags:

views:

176

answers:

6

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?

+1  A: 

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)];
}
Ólafur Waage
Should be mt_rand(0, 3) as there are only 4 items. More correctly though: $array[mt_rand(0, count($array)]
reko_t
ya my bad, fixed.
Ólafur Waage
Err, I think you meant mt_rand(0, count($ran) - 1)
Josh Davis
Yes I did, good catch. :P
reko_t
Fixed the fix of the fix :D
Ólafur Waage
A: 
$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) ];
Duroth
You would never get the first item in this list and you would go outside the array with 4
Ólafur Waage
The first $rand is about values. The original array has values ranging from 1 to 4. The second $rand is about array keys, 0 to 3.
Josh Davis
A: 

You get a random number out of an array as follows:

$randomValue = array_rand($rand,1);
Adam Libonatti-Roche
array_rand() returns a random key, not a random value.
reko_t
+4  A: 

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);
Nicky De Maeyer
A: 

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);
Manitra Andriamitondra
someone could explain the downvotes ?
Manitra Andriamitondra
Might be because you're reinventing the wheel, but it does seem like someone is out to get you.
Yuriy Faktorovich
:p ough, it hurts.
Manitra Andriamitondra
+14  A: 

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.

reko_t
+1. Only thought of this function after posting my answer, came back to edit, but found that you'd already answered.
Duroth