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.
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;
To generate a cryptographically strong random result you could use
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
- Use the
ord()function to convert the pseudo-random string from the previous step to a value between
- Compare that value to the median
128to get a random boolean value.
true as the second argument to
openssl_random_pseudo_bytes() uses a "cryptographically strong" algorithm to generate the result.
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.