PHP generates a 5-character encapsulation function with mixed English upper and lower case and non-repeating

The following is an example of an encapsulation function that uses PHP to automatically generate 5 non-repeating English characters with mixed uppercase and lowercase characters:

function generateUniqueCode($length) {
    
    
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $code = '';

    while (strlen($code) < $length) {
    
    
        $randomCharacter = $characters[random_int(0, strlen($characters) - 1)];
        if (strpos($code, $randomCharacter) === false) {
    
    
            $code .= $randomCharacter;
        }
    }

    return $code;
}

// 生成一个不重复英文大小写混排5个字符的代码
$code = generateUniqueCode(5);
echo $code;

This function uses a string containing all uppercase and lowercase English letters $characters. It randomly selects characters through a loop and checks if the selected character is already present in the generated code. If the characters are new, they are added to the code until the desired length is reached. Finally, the function returns the generated unique code.

Note that since random code is generated, there is no guarantee that each call will generate a different code. If higher uniqueness requirements are required, consider using a longer character set or increasing the length of the code.


@missingsometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/132632687