PHP more elegant way to make random 1 or 0 binary pattern

Jeff :

I am wondering if there is a more elegant way to create a random mix of 4 1's and 0's in PHP. The way I do it works but I am curious if there is a way to do the same thing with less code?

$b1 = rand(0,1);
$b2 = rand(0,1);
$b3 = rand(0,1);
$b4 = rand(0,1);

$randpattern = $b1.$b2.$b3.$b4;
KIKO Software :

Slightly shorter still:

$randpattern = substr(decbin(rand(16, 31)), -4);

The rand(16,31) will generate a random number between 16 and 31 which is made into a binary number, with decbin(), between 10000 en 11111. Finally the substr() picks only the last four characters.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=336630&siteId=1
Recommended