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

前端 未结 7 2028
不知归路
不知归路 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:10

    I don't think there's such a function built-in ; you'll probably have to code it yourself.

    To code this, you have two solutions :

    • Use a loop, to call rand() or mt_rand() until it returns a correct value
      • which means calling rand() several times, in the worst case
      • but this should work OK if N is big, and you don't have many forbidden values.
    • Build an array that contains only legal values
      • And use array_rand to pick one value from it
      • which will work fine if N is small

提交回复
热议问题