PHP random string generation code of includes upper and lower case letters

  • 2020-06-19 09:52:18
  • OfStack

Type 1: Use string function operations

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


Type 2: The idea of using array and character conversions:

 
<?php 
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 1000 cycles of testing, the efficiency of the first type is relatively high (the first type calculates about 0.02 for 1000 times, and the second type calculates about 0.06 for 1000 times)!


Related articles: