How to get a random value from 1~N but excluding several specific values in PHP?

前端 未结 7 2013
不知归路
不知归路 2020-12-10 06:56

rand(1,N) but excluding array(a,b,c,..),

is there already a built-in function that I don\'t know or do I have to implement it myself(how?)

相关标签:
7条回答
  • 2020-12-10 07:31

    Depending on exactly what you need, and why, this approach might be an interesting alternative.

    $numbers = array_diff(range(1, N), array(a, b, c));
    // Either (not a real answer, but could be useful, depending on your circumstances)
    shuffle($numbers); // $numbers is now a randomly-sorted array containing all the numbers that interest you
    // Or:
    $x = $numbers[array_rand($numbers)]; // $x is now a random number selected from the set of numbers you're interested in
    

    So, if you don't need to generate the set of potential numbers each time, but are generating the set once and then picking a bunch of random number from the same set, this could be a good way to go.

    0 讨论(0)
提交回复
热议问题