How to Generate Random Boolean Values in PHP?

Find out different ways of generating a true/false value in PHP

In this article we'll look at how we can generate random boolean (i.e. true or false) values in PHP.

Using mt_rand()

For most general use cases of generating a random boolean value, using mt_rand() would work best. This is because it is reasonably fast compared to other approaches. For example:

// PHP 4+
$randBool = (bool) mt_rand(0, 1);

For critical systems you might want to consider using random_int() instead. This is because the results of mt_rand() can be predicted.

Using rand()

It has the same syntax as mt_rand, for example:

// PHP 4+
$randBool = (bool) rand(0, 1);

We recommend using mt_rand() wherever possible as it uses the Mersenne Twister algorithm which is considerably faster than rand().

Starting PHP 7.1+, rand() is an alias of mt_rand().

Using random_int()

Starting PHP 7+, you can use random_int() as well, like so:

// PHP 7+
$randBool = (bool) random_int(0, 1);

However, using this for the purpose of generating boolean values might be an overkill for most use cases because random_int() is meant for generating cryptographically secure pseudo-random integers, and that means it requires much more processing time.

That being said, it does not mean that random_int() might not be useful in certain cases. In critical systems, for example, where unbiased results are essential, random_int() can be useful.

Using ord() and openssl_random_pseudo_bytes()

If we generate a pseudo-random string of length one, we can use ord() to convert it to a value between 0 and 255. Comparing the generated value to the median 128 should give us a random boolean value. To illustrate this, let's consider the following code:

// PHP 5+
$randBool = ord(openssl_random_pseudo_bytes(1)) >= 128;

In the code above, 128 could be substituted with the hex number 80 (which is equivalent to 128 in decimal number system). In PHP, hex numbers are prefixed with 0x, which means 0x80 equals 128. With that information, we can do this:

$randBool = ord(openssl_random_pseudo_bytes(1)) >= 0x80;

While this is a fancier way of doing the same thing as using the number 128 directly, as a good programming practice you should avoid it and write code that is easily understood and readable.

Cryptographically Strong openssl_random_pseudo_bytes():

If you want to make the result of openssl_random_pseudo_bytes() to be cryptographically strong, you can supply true as the second argument to it like so:

$randBool = ord(openssl_random_pseudo_bytes(1, true)) >= 128;

Hope you found this post useful. It was published . Please show your love and support by sharing this post.