简体   繁体   中英

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

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;

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.

Sure:

str_pad(decbin(rand(0, 15)), 4, '0', STR_PAD_LEFT);
  1. Call rand() only once. It will give a random number between 0 and 15. 15 in binary is 1111. You can also write 15 in binary to make it clear. rand(0, 0b1111)
  2. Convert into binary.
  3. If number is less than 1000 then left pad it with 0.

You can simply use a loop :

$randpattern = '' ;
while( strlen($randpattern) < 4 )
    $randpattern .= rand(0,1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM