一些随机的布尔值true / PHP中假 [英] Get random boolean true/false in PHP

查看:316
本文介绍了一些随机的布尔值true / 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 ,收益率真正,否则。当然,值 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() 随机数生成(它结束了的改善兰特())。你甚至可以去尽可能 openssl_random_pseudo_bytes()这个code:

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);

这篇关于一些随机的布尔值true / PHP中假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆