I have a PHP script where I have an array of integers, let's say $forbidden
.
I want to get a random integer from 1 to 400 that is not in $forbidden
.
Of course, I don't want any loop which breaks when rand gives a working result. I'd like something more effective.
How do you do this ?
Another method to generate a floating random number is by using the random() function. The random() function does not take any arguments. It will generate a floating-point random number between the range 0 and 1 where 1 is not included in the output. The range is defined as: [0.0, 1.0).
A random number is a number chosen as if by chance from some specified distribution such that selection of a large set of these numbers reproduces the underlying distribution. Almost always, such numbers are also required to be independent, so that there are no correlations between successive numbers.
Math. random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.
Place all forbidden numbers in an array, and use array_diff
from range(1,400)
. You'll get an array of allowed numbers, pick a random one with array_rand()
.
<?php
$forbidden = array(2, 3, 6, 8);
$complete = range(1,10);
$allowed = array_diff($complete, $forbidden);
echo $allowed[array_rand($allowed)];
This way you're removing the excluded numbers from the selection set, and nullifying the need for a loop :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With