简单的 PHP 随机数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4241300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple PHP random array
提问by Cameron
I have a simple array like this:
我有一个像这样的简单数组:
$input = array('Line1', 'Line2', 'Line3');
And want to echo one of the values randomly. I've done this before but can't remember how I did it and all the examples of array_rand seem more complex that what I need.
并希望随机回显其中一个值。我以前做过这个,但不记得我是怎么做的,array_rand 的所有例子似乎比我需要的更复杂。
Can any help? Thanks
有什么帮助吗?谢谢
回答by waiwai933
echo $input[array_rand($input)];
array_rand()returns the key, so we need to plug it back into $input
to get the value.
array_rand()返回键,因此我们需要将其插入$input
以获取值。
回答by Pekka
回答by Michael
You could use shuffle() and then just pick the first element.
您可以使用 shuffle() 然后只选择第一个元素。
shuffle($input);
echo $input[0];
But I would go with the array_rand() method.
但我会使用 array_rand() 方法。
回答by Ben Rowe
array_rand
will help you select a random key of an array. From there you can get the value.
array_rand
将帮助您选择数组的随机键。从那里你可以得到价值。
$randKey = array_rand($input);
echo $input[$randKey];