Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random boolean true/false in PHP

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?

like image 371
mgherkins Avatar asked Oct 07 '13 10:10

mgherkins


2 Answers

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); 
like image 132
Ja͢ck Avatar answered Sep 22 '22 15:09

Ja͢ck


I use a simply

rand(0,1) < 0.5 
like image 21
Alessandro Battistini Avatar answered Sep 21 '22 15:09

Alessandro Battistini