Random integer with conditions

I have a PHP script where I have an array of integers, say $forbidden.

I want to get a random integer from 1 to 400, which is not in $forbidden.

Of course, I do not want any loop to be interrupted when rand gives a working result. I would like something more efficient.

How do you do this?

+5
source share
2 answers

Put all forbidden numbers in an array and use array_difffrom range(1,400). You will get an array of allowed numbers, select random 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 remove the excluded numbers from the selection set and minimize the need for a loop :)

+10
source

. . .

0

All Articles