在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:03:09  来源:igfitidea点击:

Get random boolean true/false in PHP

phprandomboolean

提问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 0or 1already actsas a boolean value; so this:

基本上,如果该随机值是1,产率true,否则false。当然,值01已经充当为一个布尔值; 所以这:

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 ifcondition, there is no need to cast, since 0is considered false:

为了完整起见,如果您想在if条件中使用它,则无需强制转换,因为0被认为是false

if (mt_rand(0,1)) {
  // whatever
}

Note: mt_randis 4x faster than rand

注意:mt_rand比速度快 4 倍rand

The mt_rand()function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the "Mersenne Twister", which will produce random numbers four times fasterthan what the average libc rand()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
}