Reputation: 3826
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 ?
Upvotes: 5
Views: 256
Reputation: 59997
Produce an array of the allowed numbers. Find out the number in this array. Select one of those randomly.
Upvotes: 0
Reputation: 174957
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 :)
Upvotes: 10