0

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);

?>
5
  • 4
    Yes, there is a chance. random <> unique. Commented Nov 17, 2018 at 6: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. Commented Nov 17, 2018 at 6: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 en.wikipedia.org/wiki/Birthday_problem. Commented Nov 17, 2018 at 6:48
  • Very thank full to everyone , i will look into all the comments Commented Nov 17, 2018 at 6:51
  • What is the random string going to be used for? Commented Nov 17, 2018 at 8:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.