Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 呼应出一个随机变量_Php_Variables_Random_Sidebar - Fatal编程技术网

Php 呼应出一个随机变量

Php 呼应出一个随机变量,php,variables,random,sidebar,Php,Variables,Random,Sidebar,假设我有三个变量:- $first = "Hello"; $second = "Evening"; $third = "Goodnight!"; 如果我希望在我的网站侧边栏中有一个模块在每次刷新时都会发生变化,我将如何在页面上回显一个随机的模块,随机地?使用一个数组: $words = array('Hello', 'Evening', 'Goodnight!'); echo $words[rand(0, count($words)-1)]; 将它们放入一个数组中,并使用随机选择。传递给r

假设我有三个变量:-

$first = "Hello";
$second = "Evening";
$third = "Goodnight!";
如果我希望在我的网站侧边栏中有一个模块在每次刷新时都会发生变化,我将如何在页面上回显一个随机的模块,随机地

使用一个数组:

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

echo $words[rand(0, count($words)-1)];

将它们放入一个数组中,并使用随机选择。传递给
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
    $first  = "Hello";
    $second = "Evening";
    $third  = "Goodnight!";
    $array  = array($first, $second, $third);
    echo $array[mt_rand(0, count($array) - 1)];
为什么不使用此选项:

$values = array('first', 'apple', 'pear');
echo $values[array_rand($values)];

生成可以使用的更好的随机值

例如:

$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
    $first  = "Hello";
    $second = "Evening";
    $third  = "Goodnight!";
    $array  = array($first, $second, $third);
    echo $array[mt_rand(0, count($array) - 1)];

但这些不仅仅是文字,它将是相当繁重的html。因此,我可以用
$First
变量替换
First
,并在代码上方声明它并将其设置为值吗?您可以将任何需要的内容放入数组中。但是,如果您正在将“重”html转储到变量中,您可能需要重新考虑您的设计。