Get random boolean true/false in PHP(在 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);
这篇关于在 PHP 中获取随机布尔值真/假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 中获取随机布尔值真/假


- 从 PHP 中的输入表单获取日期 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01