Reputation: 1004
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
Reputation: 33238
Sure:
str_pad(decbin(rand(0, 15)), 4, '0', STR_PAD_LEFT);
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)
Upvotes: 4
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
Reputation: 2438
You can simply use a loop :
$randpattern = '' ;
while( strlen($randpattern) < 4 )
$randpattern .= rand(0,1);
Upvotes: 3