You generate a string of 5 characters, where each character has a value between 97 and 122 inclusive.
As such, there are 122 - 97 + 1 = 26 possibilities per character.
And there are 265 = 11 881 376 combinations in total
If you have generated N strings so far, the chance that the next generated string will be a duplicate is N / 11 881 376.
If it's important that you get no duplicates, it doesn't matter how unlikely it is for it to happen. Even if the chance of this happening is one in a billion, you could still get ten duplicates on the first couple of runs. It's not impossible, just unlikely.
You need to store all previously generated keys and then make sure the newly created key is not among those.
function generator($lenght=5) {
$keys = somehowReadStoredKeys();
// if $keys is not sorted, you should definitely
array_sort($keys);
$generate = true;
while ($generate) {
$uniqueKey = '';
for($i = 0; $i < $lenght; $i++) {
$uniqueKey .= chr(rand(97,122));
}
if (array_search($uniqueKey, $keys) === false)
$generate = false;
}
return $uniqueKey;
}
Do note that this approach won't be acceptable if the number of previously generated keys are significant compared to the number of possible keys. When half the keys have been used, the above while loop would have to run twice for every other generated key (on average). When all the keys have been used, it would run an extra round every time (which means it would loop infinitely).