Get random boolean true/false in PHP -
what elegant way random boolean true/false in php?
i can think of:
$value = (bool)rand(0,1); but casting integer boolean bring disadvantages?
or "official" way this?
if don't wish have boolean cast (not there's wrong that) can make boolean this:
$value = rand(0,1) == 1; basically, if random value 1, yield true, otherwise false. of course, value of 0 or 1 acts boolean value; this:
if (rand(0, 1)) { ... } is valid condition , work expected.
alternatively, can use mt_rand() random number generation (it's improvement on rand()). go far openssl_random_pseudo_bytes() code:
$value = ord(openssl_random_pseudo_bytes(1)) >= 0x80; update
in php 7.0 able use random_int(), generates cryptographically secure pseudo-random integers:
$value = (bool)random_int(0, 1);
Comments
Post a Comment