gpt4 book ai didi

php - 回显一个随机变量

转载 作者:可可西里 更新时间:2023-11-01 12:41:10 26 4
gpt4 key购买 nike

假设我有三个变量:-

$first = "Hello";
$second = "Evening";
$third = "Goodnight!";

我如何将一个随机的回显到页面上,因为我希望在我的网站侧边栏中有这个模块,它会在每次刷新时发生变化,随机

最佳答案

将它们放入一个数组中,然后使用 rand() 从中随机选择.传递给 rand() 的数字边界对于下限为零,作为数组中的第一个元素,并且比数组中的元素数少一个。

$array = array($first, $second, $third);
echo $array[rand(0, count($array) - 1)];

例子:

$first = 'first';
$second = 'apple';
$third = 'pear';

$array = array($first, $second, $third);
for ($i=0; $i<5; $i++) {
echo $array[rand(0, count($array) - 1)] . "\n";
}

// Outputs:
pear
apple
apple
first
apple

或者更简单,通过调用 array_rand($array)并将结果作为数组键传回:

// Choose a random key and write its value from the array
echo $array[array_rand($array)];

关于php - 回显一个随机变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8676183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com