在 PHP 中获取随机布尔值真/假
在 PHP 中获得随机布尔真/假的最优雅的方法是什么?
What would be the most elegant way to get a random boolean true/false in PHP?
我能想到:
$value = (bool)rand(0,1);
但是将整数转换为布尔值有什么缺点吗?
But does casting an integer to boolean bring any disadvantages?
或者这是一种官方"的方式来做到这一点?
Or is this an "official" way to do this?
推荐答案
如果您不希望进行布尔类型转换(并不是说这有什么问题),您可以像这样轻松地将其设置为布尔值:
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;
基本上,如果随机值为1
,则产生true
,否则false
.当然,0
或 1
的值已经充当 布尔值;所以这个:
Basically, if the random value is 1
, yield true
, otherwise false
. Of course, a value of 0
or 1
already acts as a boolean value; so this:
if (rand(0, 1)) { ... }
是一个完全有效的条件,将按预期工作.
Is a perfectly valid condition and will work as expected.
或者,您可以使用 mt_rand()
生成随机数(这是对 rand()
).您甚至可以使用以下代码达到 openssl_random_pseudo_bytes()
:
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:
$value = ord(openssl_random_pseudo_bytes(1)) >= 0x80;
更新
在 PHP 7.0 中,您将能够使用 random_int()
,它会生成加密安全的伪随机数整数:
Update
In PHP 7.0 you will be able to use random_int()
, which generates cryptographically secure pseudo-random integers:
$value = (bool)random_int(0, 1);
相关文章