PHP how to get a random number that is different f

2019-02-28 01:42发布

问题:

Example: I have an array with 3 values:

0 = 1
1 = 4
2 = 5

I want to get a random number like

$random = rand(1, 5);

But I need to get a number that is different from the array values. I need it to return 2 or 3.

回答1:

This should work for you:

(Here I create the range from where you get your random number with range(). Then I get rid of these numbers which you don't want with array_diff(). And at the end you can simply use array_rand() to get a random key/number)

<?php

    $blacklist = [1, 4, 5];
    $range = range(1, 5);
    $randomArray = array_diff($range, $blacklist);
    echo $randomArray[array_rand($randomArray, 1)];

?>

output:

2 or 3

EDIT:

Just did some benchmarks and the method with the loop is much slower than the code above!

I created an array(blacklist) from 1...100'000 and a random number array from 1... 100'001.

So that script should only create one/unique random number. With the loop method you get an error:

Fatal error: Maximum execution time of 30 seconds exceeded

And with the posted code above it takes 1.5 sec in average.