For critical systems, for example where unbiased results are essential, you can generate a cryptographically secure random boolean value using either of the following:
Please note that using either of the above functions would require some amount of processing time to generate a cryptographically secure random value. Therefore, for simpler cases, you should consider using a less CPU-intensive approach instead.
Using random_int()
You can use the random_int()
function to generate a cryptographically secure pseudo-random integer, which can then be cast to a boolean like so:
// PHP 7+ $randNum = random_int(0, 1); $randBool = (bool) $randNum;
Using ord()
and openssl_random_pseudo_bytes()
To generate a cryptographically strong random result you could use ord()
and openssl_random_pseudo_bytes()
functions together like so:
// PHP 5+ $pseudoRandStr = openssl_random_pseudo_bytes(1, true); $randNum = ord($pseudoRandStr); $randBool = $randNum >= 128;
This works in the following way:
- Generate a cryptographically strong pseudo-random string of bytes of length one using
openssl_random_pseudo_bytes()
; - Use the
ord()
function to convert the pseudo-random string from the previous step to a value between0
and255
; - Compare that value to the median
128
to get a random boolean value.
Passing true
as the second argument to openssl_random_pseudo_bytes()
uses a "cryptographically strong" algorithm to generate the result.
Wherever possible, use random_int()
instead, or a polyfill for it.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.