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

2022-08-30 22:31:11
$apple="";
$banana="";
$apple="Red";
$banana="Blue";

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

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


答案 1

怎么样:

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

答案 2

代码问题

PHP 函数采用两个数字作为输入,以形成从中选取随机数的范围。您不能向它提供字符串。rand()

请参阅 PHP 手册页以获取 rand()。

解决 方案

您可以使用 array_rand()

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

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

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

推荐