PacPac
PacPac

Reputation: 261

Pick a random number that is not is a set of number in PHP

I need to pick a random number from 31 to 359.

rand(31, 359);

I need the number is not part from this array of numbers:

$badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360);

How can I do this please?

Thanks.

Upvotes: 0

Views: 111

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78974

I would probably do this as it completes when one is found:

while(in_array($rand = rand(31, 359), $badNumbers));
echo $rand;

Here is another way using an array:

$good  = array_diff(range(31, 359), $badNumbers);
echo $good[array_rand($good)];

Or randomize and choose one:

shuffle($good);
echo array_pop($good);

The array approaches are useful if you need to pick more than one random number. Think array_rand again or array_slice for the second one.

Upvotes: 3

DylanScript
DylanScript

Reputation: 94

This creates an array containing only the good numbers and returns a random value.

$goodNumbers = array_diff(range(31,359),[$badNumbers]);
$randIndex = array_rand($goodNumbers);
$randomGoodNumber = $goodNumbers[$randIndex];

Upvotes: 0

Qirel
Qirel

Reputation: 26460

What you need is a recursive function (which is a function that keeps calling itself with a condition to break out once the requirement is met) or an infinite loop that breaks when it finds a number that isn't in the array. What this means is that you try to generate a number, but if that number is in the list, you try again - and keep doing that until satisfied.

Here's an example,

$badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360);

function rand_unique(array $array, int $new) {
    if (in_array($new, $array)) {
        return rand_unique($array, $new);
    }
    return $new;
}
$newRand = rand_unique($badNumbers, rand(31, 359));
echo $newRand;

Upvotes: 3

Related Questions