我不明白 PHP“每日报价”教程
在本教程中的每日灵感部分,他说:
$quote = array(
1 => "Quote 1",
2 => "Quote 2",
3 => "Quote 3",
4 => "Quote 4",
5 => "Quote 5",
);
srand ((double) microtime() * 1000000);
$randnum = rand(1,5);
echo"$quote[$randnum]";
我不明白他在这里做什么(字面意思):
srand ((double) microtime() * 1000000);
你能帮我理解这是做什么的吗?
我知道 srand() 是:
为随机数生成器提供种子
但是他为什么要这样做,这样做的意义何在?
顺便说一句:我会这样说:
<?php
$quotes = array(
"one",
"two",
"three"
);
echo $quotes[rand(0,count($quotes)-1)];
?>
这有什么问题吗?
In this tutorial in the part of Daily inspirations he says:
$quote = array(
1 => "Quote 1",
2 => "Quote 2",
3 => "Quote 3",
4 => "Quote 4",
5 => "Quote 5",
);
srand ((double) microtime() * 1000000);
$randnum = rand(1,5);
echo"$quote[$randnum]";
I do not understand what he is doing (literally) here:
srand ((double) microtime() * 1000000);
Could you please help me understand what this does?
I know srand() is to:
Seed the random number generator
But why does he do this, what's the point of it?
By the way: I would have gone with something like this:
<?php
$quotes = array(
"one",
"two",
"three"
);
echo $quotes[rand(0,count($quotes)-1)];
?>
Is there anything wrong with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
大多数随机数生成器实际上并不是随机的;它们生成的下一个数字是使用一个简单但很大的函数根据之前生成的数字计算出来的。播种 RNG 会为其提供一个“先前”的工作编号,因为很多时候它们每次都从相同的已知状态开始。
Most random number generators aren't actually random; the next number they generate is calculated using a simple-yet-large function from previous numbers that have been generated. Seeding the RNG gives it a "previous" number to work from, since many times they start from the same known state each time.
在 PHP 4.2 之前,您需要为随机发生器“播种”,才能使其真正成为“随机”。现在播种随机发生器是没有意义的。
文档指出:
请参阅:http://php.net/manual/en/function.srand.php
您的解决方案同样有效。
Before PHP 4.2 you needed to 'seed' the randomizer in order for it to actually be 'random.' Now it's pointless to seed the randomizer.
The docs state:
see: http://php.net/manual/en/function.srand.php
Your solution is just as effective.
调用 srand() 的目的是提供“更好”的随机数。但调用 srand() 带来“更多随机”数字并不一定正确。从
PHP 4.2
开始,调用srand()
不再是必需的,因为 PHP 在内部执行此操作。The idea behind calling
srand()
is to provide "better" random numbers. But it is not necessarily true that callingsrand()
brings "more random" numbers. SincePHP 4.2
it is not essential to callsrand()
because PHP does this internal.这只是一个二十年前的教程中的产物(使用另一个!):
mt_rand
应该优于rand
,因为它更快且“更随机”(即它提供更多程度的无偏随机变量)PS:我建议使用
array_rand
在这里,因为您不需要关心确切的键。This simply is an artifact from a twenty-year-old tutorial (use another one!):
mt_rand
should be preferred overrand
, as it is faster and "more random" (i.e. it gives unbiased random variables in more degrees)PS: I would recommend using
array_rand
here, because you don't need to care about the exact keys.