-1

Below is the code which im using to generate random string , is there any chance that i might get duplicate

<?php

echo random_int(100,999).substr(uniqid(),-4);

?>
T Jagadish Gupta
  • 101
  • 1
  • 3
  • 15
  • 4
    Yes, there is a chance. random <> unique. – user3783243 Nov 17 '18 at 06:16
  • yeap! as stated above without comparison is impossible to know (unless external logic or feature guarantee you such behavior). You need to check if value is generated before and for that reason you need to store all previous generated values. – oetoni Nov 17 '18 at 06:45
  • 2
    A rough back-of-the-envelope calculation says that this can at most produce 66,435 unique strings. It only takes a fraction of that to hit a 50% probability to generate a duplicate. See https://en.wikipedia.org/wiki/Birthday_problem. – deceze Nov 17 '18 at 06:48
  • Very thank full to everyone , i will look into all the comments – T Jagadish Gupta Nov 17 '18 at 06:51
  • What is the random string going to be used for? – SpacePhoenix Nov 17 '18 at 08:08

1 Answers1

2

Yes, in fact there is a relatively likely chance that you will get a duplicate. Consider the following test:

$arr = [];
$i = 0;
while (1) {
    echo ++$i . PHP_EOL;
    $val = random_int(100,999).substr(uniqid(),-4);
    if (in_array($val, $arr)) break;
    $arr[] = $val;
}

Took me less than 5000 iterations on the first try to hit a duplicate. The only way to 100% guarantee that a string is unique is to compare it against the others in a set and try again if it matches one of them. If all you need is unique - just use an autoincrement.