Random ID/Number Generator in PHP

前端 未结 4 1415
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 05:29

I am building a list of \"agent id\'s\" in my database with the following requirements:

  1. The ID must be 9 digits long (numeric only)
  2. The ID may not con
4条回答
  •  臣服心动
    2021-01-17 06:32

    1. Do not re-seed the RNG on every call like that, unless you want to completely blow the security of your random numbers.
    2. Unless your PHP is very old, you probably don't need to re-seed the RNG at all, as PHP seeds it for you on startup and there are very few cases where you need to replace the seed with one of your own choosing.
    3. If it's available to you, use mt_rand instead of rand. My example will use mt_rand.

    As for the rest -- you could possibly come up with a very clever mapping of numbers from a linear range onto numbers of the form you want, but let's brute-force it instead. This is one of those things where yes, the theoretical upper bound on running time is infinite, but the expected running time is bounded and quite small, so don't worry too hard.

    function createRandomAGTNO() {
      do {
        $agt_no = mt_rand(100000000,900000000);
        $valid = true;
        if (preg_match('/(\d)\1\1/', $agt_no))
          $valid = false; // Same digit three times consecutively
        elseif (preg_match('/(\d).*?\1.*?\1.*?\1/', $agt_no))
          $valid = false; // Same digit four times in string
      } while ($valid === false);
      return $agt_no;
    }
    

提交回复
热议问题