Home>Article>Backend Development> How to generate unique serial numbers in php
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)].
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:
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!