0

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.

2
  • Array_unique will eliminate not unique elements, so instead of 4 strings you will get three or two or even one. Commented Jun 8, 2017 at 20:19
  • 2
    Store all previously created strings in a collection and loop until your method creates one that isn't included yet. Commented Jun 8, 2017 at 20:19

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.