Reputation: 960
The following function will create a random string output what is the best way to prevent duplicate outputs / collisions if called multiple times.
function random_string($length) {
$key = '';
$keys = array_merge(range('A', 'Z'), range('a', 'z'), array('_'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
echo "First : " . random_string(rand(3, 50));
//These have a small percentage of a chance of matching the previous random output lets eliminate all possibility of getting the same output.
echo "Second : " . random_string(rand(3, 50));
echo "Third : " . random_string(rand(3, 50));
echo "Fourth : " . random_string(rand(3, 50));
I did read on the PHP documentation that array_unique could achieve what i want but would it be the best solution or is there a more efficient way.
Upvotes: 0
Views: 523
Reputation: 75629
or is there a more efficient way
You are heading to "overengeneering land", trying to fix things you cannot even name :) Is it slow? Sluggish? Then profile and fix relevant parts. "Efficient" is buzzword w/o defining what efficiency means for you.
what is the best way to prevent duplicate outputs / collisions if called multiple times
First, I'd use hashing functions with detailed (i.e. seconds or millis) timestamp + some mt_rand as input like instead. It's limited in length but you can call it multiple times and concatenate results (+ trim if needed). And if you want to be 1000% the value was never returned before, you must keep track of them, however you most likely can assume this is not going to happen if you will have input string long enough
Upvotes: 1
Reputation: 54841
Here's a simple solution:
// array to store required strings
$stringsCollection = [];
// 4 is the number of strings that you need
while (sizeof($stringsCollection) != 4) {
// generate new string
$randString = random_string($length);
// if string is not in `stringsCollection` - add it as a key
if (!isset($stringsCollection[$randString])) {
$stringsCollection[$randString] = 1;
}
}
print_r(array_keys($stringsCollection));
Upvotes: 2