Home > Backend Development > PHP Tutorial > How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?

How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-09-21 14:12:54
Original
1269 people have browsed it

How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?

Reply content:

How to combine letters and numbers in PHP random numbers? The first two are letters followed by numbers?

The idea mentioned above is correct. It is normal for repetition to occur if the random number is too large. I wrote a method according to your needs. If you are interested, you can run it a million times to see what the probability of repetition is.

<code>function getRandomString($prefixLength = 2, $suffixLength = 6) {
    $t = '';
    for ($i=0; $i<$prefixLength; $i++) {
        $salt = mt_rand(1000, 9999);
        if ($salt % 2) {
            $t .= chr(mt_rand(97,122));
        } else {
            $t .= chr(mt_rand(65,90));
        }
    }
    $min = intval(str_pad('1', $suffixLength, '0', STR_PAD_RIGHT));
    $max = intval(str_repeat('9', $suffixLength));
    return $t . mt_rand($min, $max);
}

</code>
Copy after login

First generate random letters and then generate random numbers, but this may cause duplication. If you want to avoid duplication as much as possible, you can only start with the following numbers. Please try the following example

<code>function randomKey(){
    $re = '';
    $letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    while(strlen($re)<2) {
        $re .= $letter[rand(0, strlen($letter)-1)]; /** 从$letter中随机产生一个字符 */
    }
    $_rand = mt_rand(10000000, 99999999); /** 生成8位随机数 */
    list($usec, $sec) = explode(" ", microtime()); /** 获取微秒时间戳 */
    $microtime = str_replace(".", "", ((float)$usec + (float)$sec)); /** 处理字符串 */
    
    $result = $re.$_rand.$microtime;
}</code>
Copy after login

The random number generated in this way may be a bit long. You can remove the random number or directly use letters and subtle timestamps. For reference only

Can’t you just put two random letters in some random arrays and then splice them together? Or have special needs?

Related labels:
php
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template