PHP 从两个字符串中选择一个随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8742175/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:23:40  来源:igfitidea点击:

PHP Select a Random String from Two Strings

phprandom

提问by TheBlackBenzKid

$apple="";
$banana="";
$apple="Red";
$banana="Blue";

$random(rand($apple, $banana);
echo $random;

How can I select a random string (fast) via PHP?

如何通过 PHP 选择随机字符串(快速)?

回答by Razvan Grigore

What about:

关于什么:

$random = rand(0, 1) ? 'Red' : 'Blue';

回答by Treffynnon

Issue with your code

你的代码有问题

The PHP rand()function takes two numbers as input to form the range to pick a random number from. You cannot feed it strings.

PHPrand()函数将两个数字作为输入以形成从中选择随机数的范围。你不能喂它字符串。

See the PHP manual page for rand().

参见PHP 手册页rand()

Solutions

解决方案

You can use array_rand():

您可以使用array_rand()

$strings = array(
    'Red',
    'Blue',
);
$key = array_rand($strings);
echo $strings[$key];


Another option is to use shuffle().

另一种选择是使用shuffle().

$strings = array(
    'Red',
    'Blue',
);
shuffle($strings);
echo reset($strings);

回答by Manse

Use an array :

使用数组:

$input = array("Red", "Blue", "Green");
echo $input[array_rand($input)];

回答by DaveRandom

array_rand()is probably the best way:

array_rand()可能是最好的方法:

$varNames = array('apple','banana');
$var = array_rand($varNames);
echo ${$varNames[$var]};

回答by OptimusCrime

The function rand()has two parameters: a lower-limit for a random number and an upper limit. You can not use variables like that because it is not the way the function works.

该函数rand()有两个参数:随机数的下限和上限。你不能使用这样的变量,因为它不是函数的工作方式。

Take a look at the documentation:
http://php.net/rand

看一下文档:http:
//php.net/rand

A simple way to achieve what you want is this:

实现您想要的一种简单方法是:

$array = array();
$array[0] = 'banana';
$array[1] = 'orange';
$randomSelected = $array[rand(0,(count($array)-1))];

As far as I've read, this solution is faster than array_rand(). I can see if I can find the source of that.

据我所知,这个解决方案比array_rand(). 我可以看看我能不能找到它的来源。

回答by Pete_1

Ran into this old question that tops google's results. You can have more than two options and still get it all on one line.

遇到了这个在谷歌搜索结果中排名第一的老问题。您可以有两个以上的选择,并且仍然可以在一行中获得所有选项。

echo ['green', 'blue', 'red'][rand(0,2)];