PHP random string generation code (including upper and lower case letters)_PHP tutorial

WBOY
Release: 2016-07-21 15:03:03
Original
1128 people have browsed it

The first method: Use string functions to operate

Copy the code The code is as follows:

function createRandomStr($length){
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62 characters
$strlen = 62;
while($length > $strlen){
$str .= $str;
$strlen += 62;
}
$str = str_shuffle($str);
return substr($str,0,$length);
}
echo createRandomStr(10);


Second: Using the idea of ​​array and character conversion:

Copy Code The code is as follows:

function createRandomStr($length){
$str = array_merge(range(0,9),range( 'a','z'),range('A','Z'));
shuffle($str);
$str = implode('',array_slice($str,0,$length ));
return $str;
}
echo createRandomStr(10);


After looping 1000 times, the first method is more efficient (first The first calculation is about 0.02 seconds a thousand times, and the second calculation is about 0.06 seconds a thousand times)!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327871.htmlTechArticleThe first method: Use string function operation to copy the code. The code is as follows: ?php function createRandomStr($length){ $ str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';/...
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template