Home  >  Article  >  Backend Development  >  How to generate unique serial numbers in php

How to generate unique serial numbers in php

王林
王林Original
2020-09-01 13:58:003522browse

How to generate unique serial numbers in php: You can use the built-in function [mt_rand()] to achieve this. The [mt_rand()] function is used to generate random integers, for example, to generate a number between 10 and 100. A random integer between , the specific code is: [mt_rand(10, 100)].

How to generate unique serial numbers in php

php provides us with the function mt_rand() specially used to generate random numbers, which uses the Mersenne Twister algorithm to generate random integers.

Tip: This function is a better choice for generating random values, returning results 4 times faster than the rand() function.

(Recommended tutorial: php video tutorial)

Example:

Generate a value between 10 and 100 (including 10 and 100) Random integer

mt_rand (10,100)

Function syntax:

mt_rand();
or
mt_rand(min,max);

Parameters:

  • ##min Optional. Specifies the minimum number to return. The default is 0.​

  • #max Optional. Specifies the maximum number to return.

Return value:

A random integer between min (or 0) and max (or mt_getrandmax()) (including boundary values). If max < min returns FALSE.

(Related recommendations:

php training)

Code implementation:

//生成随机码
    function GetRandStr($len=10){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars);
        $output = "";
        for ($i=0; $i<$len; $i++)
        {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
    //生成不在$arr中的序列号
    function getUniqueSerial($arr){
        $str = GetRandStr(64);
        if(in_array($str, $arr)){
            $str = getUniqueSerial($arr);
        }
        return $str;  
    }

The above is the detailed content of How to generate unique serial numbers in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn