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 ?
Place all forbidden numbers in an array, and use
array_difffromrange(1,400). You’ll get an array of allowed numbers, pick a random one witharray_rand().This way you’re removing the excluded numbers from the selection set, and nullifying the need for a loop 🙂