在 PHP 中获取随机布尔值真/假
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19222716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get random boolean true/false in PHP
提问by Max Girkens
What would be the most elegant way to get a random boolean true/false in PHP?
在 PHP 中获得随机布尔值真/假的最优雅方法是什么?
I can think of:
我能想到:
$value = (bool)rand(0,1);
But does casting an integer to boolean bring any disadvantages?
但是将整数转换为布尔值会带来任何缺点吗?
Or is this an "official" way to do this?
或者这是一种“官方”的方式来做到这一点?
回答by Ja?ck
If you don't wish to have a boolean cast (not that there's anything wrong with that) you can easily make it a boolean like this:
如果你不希望有一个布尔类型转换(不是说这有什么问题)你可以很容易地把它变成一个像这样的布尔值:
$value = rand(0,1) == 1;
Basically, if the random value is 1
, yield true
, otherwise false
. Of course, a value of 0
or 1
already actsas a boolean value; so this:
基本上,如果该随机值是1
,产率true
,否则false
。当然,值0
或1
已经充当为一个布尔值; 所以这:
if (rand(0, 1)) { ... }
Is a perfectly valid condition and will work as expected.
是一个完全有效的条件,将按预期工作。
Alternatively, you can use mt_rand()
for the random number generation (it's an improvement over rand()
). You could even go as far as openssl_random_pseudo_bytes()
with this code:
或者,您可以mt_rand()
用于随机数生成(这是对 的改进rand()
)。您甚至可以openssl_random_pseudo_bytes()
使用以下代码:
$value = ord(openssl_random_pseudo_bytes(1)) >= 0x80;
Update
更新
In PHP 7.0 you will be able to use random_int()
, which generates cryptographically secure pseudo-random integers:
在 PHP 7.0 中,您将能够使用random_int()
,它生成加密安全的伪随机整数:
$value = (bool)random_int(0, 1);
回答by Alessandro Battistini
I use a simply
我用一个简单的
rand(0,1) < 0.5
回答by jpenna
Just for completeness, if you want use it in an if
condition, there is no need to cast, since 0
is considered false
:
为了完整起见,如果您想在if
条件中使用它,则无需强制转换,因为0
被认为是false
:
if (mt_rand(0,1)) {
// whatever
}
Note: mt_rand
is 4x faster than rand
注意:mt_rand
比速度快 4 倍rand
The
mt_rand()
function is a drop-in replacement for the olderrand()
. It uses a random number generator with known characteristics using the "Mersenne Twister", which will produce random numbers four times fasterthan what the average libcrand()
provides.
该
mt_rand()
功能是旧的rand()
. 它使用具有已知特性的随机数生成器,使用“Mersenne Twister”,生成随机数的速度是 libcrand()
提供的平均速度的四倍。
回答by des1roer
php stan recomended
php stan 推荐
1 === random_int(0, 1)
回答by Cameron Wilby
Technically not as performant as the other answers - but you could also utilize type coercion:
从技术上讲,性能不如其他答案 - 但您也可以利用类型强制:
if(!!rand(0, 1)) {
// random
}