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?
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?
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:
Basically, if the random value is
1
, yieldtrue
, otherwisefalse
. Of course, a value of0
or1
already acts as a boolean value; so this: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 overrand()
). You could even go as far asopenssl_random_pseudo_bytes()
with this code:Update
In PHP 7.0 you will be able to use
random_int()
, which generates cryptographically secure pseudo-random integers:I use a simply