回应随机变量

Fra*_*ank 7 php random variables sidebar

假设我有三个变量: -

$first = "Hello";
$second = "Evening";
$third = "Goodnight!";
Run Code Online (Sandbox Code Playgroud)

我如何将随机的一个回显到页面上,因为我希望在我的网站侧边栏中将此模块随机更改每次刷新?

Mic*_*ski 17

将它们放入一个数组中并随机选择rand().传递给的数字边界rand()对于较低的数字为零,作为数组中的第一个元素,并且小于数组中元素的数量.

$array = array($first, $second, $third);
echo $array[rand(0, count($array) - 1)];
Run Code Online (Sandbox Code Playgroud)

例:

$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
Run Code Online (Sandbox Code Playgroud)

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

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


Mar*_*c B 8

使用数组:

$words = array('Hello', 'Evening', 'Goodnight!');

echo $words[rand(0, count($words)-1)];
Run Code Online (Sandbox Code Playgroud)

  • 您可以将任何想要的东西放入数组中.但是如果你把"沉重"的html倾倒在变量中,你可能想重新考虑你的设计. (3认同)

Cyc*_*ode 5

为什么不用array_rand()于此目的:

$values = array('first', 'apple', 'pear');
echo $values[array_rand($values)];
Run Code Online (Sandbox Code Playgroud)