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 中获取随机布尔值真/假
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
