I know the uniqid()
method to create lots of unique ids with a length of 7 or more, but what I want to create is a length of 5 unique id with no collision.
Is it possible to create 220.000 unique id's with a length of 5 and check if there is any collision?
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 and always collision is always less that 0.02 which makes the function efficient for a 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;
}
Take a look at this article
It explains how to generate short unique ids from your bdd ids, like youtube does.
Actually, the function in the article is very related to php function base_convert which converts a number from a base to another (but is only up to base 36).
I wanted to use uniqid()
function for making a string of particular length. Hence I experimented and came up with the following code:
<?php
$number = uniqid();
$varray = str_split($number);
$len = sizeof($varray);
$otp = array_slice($varray, $len-5, $len);
$otp = implode(",", $otp);
$otp = str_replace(',', '', $otp);
print_r($otp);
?>
This works fine for me, as long as your site doesn't generate OTPs at a very fast rate, this should work fine!