How to get random value out of an array

2019-01-03 10:07发布

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?

14条回答
一夜七次
2楼-- · 2019-01-03 10:26

One line: $ran[rand(0, count($ran) - 1)]

查看更多
Emotional °昔
3楼-- · 2019-01-03 10:27

The array_rand function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:

$myArray = array(1, 2, 3, 4, 5);

// Random shuffle
shuffle($myArray);

// First element is random now
$randomValue = $myArray[0];
查看更多
Emotional °昔
4楼-- · 2019-01-03 10:27
$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) ];
查看更多
趁早两清
5楼-- · 2019-01-03 10:27

I'm basing my answer off of @ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:

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

For more context, see my question over at Passing/Returning references to object + changing object is not working

查看更多
我只想做你的唯一
6楼-- · 2019-01-03 10:28

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)];
查看更多
干净又极端
7楼-- · 2019-01-03 10:29

Use rand() to get random number to echo random key. In ex: 0 - 3

$ran = array(1,2,3,4);
echo $ran[rand(0,3)];
查看更多
登录 后发表回答