mysql - create unique id with a length of 5 in php -


i know uniqid()method create lots of unique ids length of 7 or more! want create length of 5 unique id no collision. possible create 220.000 unique id's length of 5 , check if there collision.

thanks

you can try

for($i = 0; $i < 10 ; $i++) {     echo randstring(5),php_eol ; } 

output

7fh96 g93fd 97q7e 90wku 7vby9 4678f s11oe 67688 19d36 kc1bq 

simple collision test

$hash = array(); $collision = 0; while ( count($hash) < 220000 ) {     $r = randstring(5);     if (isset($hash[$r])) {         $collision ++;         continue;     }     $hash[$r] = 1; }  print(($collision / 220000)  * 100 . "% - ($collision)"); 

tested 100,000 times , collision less 0.02 makes function efficient 5 character set

0.011818181818182% - (26) 

function used

function randstring($length) {     $char = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789";     $char = str_shuffle($char);     for($i = 0, $rand = '', $l = strlen($char) - 1; $i < $length; $i ++) {         $rand .= $char{mt_rand(0, $l)};     }     return $rand; } 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -