You can generate a random boolean value in PHP using the
mt_rand() function, and casting its result to a boolean like so:
// PHP 4+ $randBool = (bool) mt_rand(0, 1);
For more common cases, using
mt_rand() is a good choice as it is typically faster than using more secure methods (such as with
random_int(), etc.). However, for critical systems you might want to consider using the latter instead as the result of
mt_rand() can be predicted.
Although you can use the
rand() function instead of
mt_rand() as well, it is recommended to use
mt_rand() wherever possible as it uses the Mersenne Twister algorithm (which is considerably faster than
rand()). Also, starting with PHP 7.1+,
rand() is merely an alias of
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.