我正试图使用下面的代码在新的网页刷新时回显一个随机url,但我无法使其工作
<?php
$url=array(
'http://www.google.com',
'http://www.in.gr',
'http://www.yahoo.gr'
);
$random=rand(1,count($url));
echo $url[$random];
?>
谢谢大家!
更换
$random=rand(1,count($url));
带
$random = mt_rand(0, count($url) - 1);
我还没有尝试过,但它应该可以工作。。。我希望。。
<?php
$url=array(
'http://www.google.com',
'http://www.in.gr',
'http://www.yahoo.gr'
);
$rand = rand(0, 2);
echo $url[$rand];
数组索引从0开始,长度为-1。http://php.net/manual/en/function.rand.php第一个值是最小值。这是0。第二个值是最大值,它是数组的最后一个索引。
<?php
$url=array(
'http://www.google.com',
'http://www.in.gr',
'http://www.yahoo.gr'
);
$random=rand(0,count($url));
echo $url[$random];
?>
更改为:
$random=rand(0, count($url)-1);
代码的问题在于,您将最小值设置为1,将最大值设置为URL总数。数组是从零开始的,因此需要0作为最小值,需要count($url)-1
作为最大值。在这种情况下,您有3个URL,但第三个URL在$url[2]
而不是$url[3]
中。
试试这个
<?php
$url = array(
'http://www.google.com',
'http://www.in.gr',
'http://www.yahoo.gr'
);
$random = array_rand($input);
echo $url[$random];
?>
数组的第一个键是0。因此,将rand函数更改为:
rand( 0,count($url) - 1 );
好吧,首先改变这个:
$random=rand(1,count($url));
至
$random=rand(0,count($url) - 1);
数组起始索引为0