Example: I have an array with 3 values:
0 = 1
1 = 4
2 = 5
I want to get a random number like
$random = rand(1, 5);
But I need to get a number that is different from the array values. I need it to return 2 or 3.
Example: I have an array with 3 values:
0 = 1
1 = 4
2 = 5
I want to get a random number like
$random = rand(1, 5);
But I need to get a number that is different from the array values. I need it to return 2 or 3.
This should work for you:
(Here I create the range from where you get your random number with
range()
. Then I get rid of these numbers which you don't want witharray_diff()
. And at the end you can simply usearray_rand()
to get a random key/number)output:
EDIT:
Just did some benchmarks and the method with the loop is much slower than the code above!
I created an array(blacklist) from 1...100'000 and a random number array from 1... 100'001.
So that script should only create one/unique random number. With the loop method you get an error:
And with the posted code above it takes 1.5 sec in average.