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:43

Another approach through flipping array to get direct value.

Snippet

$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));

array_rand return key not value. So, we're flipping value as key.

Note: PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.

查看更多
等我变得足够好
3楼-- · 2019-01-03 10:48
$value = $array[array_rand($array)];
查看更多
登录 后发表回答