Random integer with conditions
php, random
Solution
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 :)
Problem
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 ?