Jeff
Jeff

Reputation: 1004

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;

Upvotes: 1

Views: 555

Answers (3)

Dharman
Dharman

Reputation: 33238

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.

Upvotes: 4

KIKO Software
KIKO Software

Reputation: 16688

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.

Upvotes: 5

Joffrey Schmitz
Joffrey Schmitz

Reputation: 2438

You can simply use a loop :

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

Upvotes: 3

Related Questions