Get random boolean true/false in PHP

PhpRandomBoolean

Php Problem Overview


What would be the most elegant way to get a random boolean true/false in 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?

Php Solutions


Solution 1 - Php

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 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.

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;

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

Solution 2 - Php

I use a simply

rand(0,1) < 0.5

Solution 3 - Php

Just for completeness, if you want use it in an if condition, there is no need to cast, since 0 is considered false and mt_rand produces random integers in the range:

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

Note: mt_rand is 4x faster than 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 faster than what the average libc rand() provides. (Source: https://www.php.net/manual/en/function.mt-rand.php)

Solution 4 - Php

php stan recomended

1 === random_int(0, 1)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmgherkinsView Question on Stackoverflow
Solution 1 - PhpJa͢ckView Answer on Stackoverflow
Solution 2 - PhpAlessandro BattistiniView Answer on Stackoverflow
Solution 3 - PhpjpennaView Answer on Stackoverflow
Solution 4 - Phpdes1roerView Answer on Stackoverflow