Trix Trix - 4 months ago 14
PHP Question

php - How to create a random bit stream

How can I generate following random array:

array(1, 0 , 0, 1, 1, 1, 1, 0, 1, 0, 0)


with
length = n
?

Of course, always the
for
solution is out there. But is there any One-line simple solution on this, like any combination of
array_fill
and
mt_rand(0, 1)
?

Answer

You can use combination of array_map and range (or array_fill if you need) to generate random values.

$length = 10;
$randBits = array_map(
    function () {
        return mt_rand(0, 1);
    },
    range(0, $length - 1)
);

Working example