How can I generate unique alphanumeric?

Hi, how can i generate unique alphanumeric like this example

EA070998

EA011575

HK144331

A0058579

Thank you in advance.

Smells like homework. There’s about 3 dozen ways to do this. Look over the functions rand() and substr() for ways it might be done.

Or you can try this out.

  1. Make an array with one of each letter of the alphabet.
  2. Shuffle it using the shuffle() function.
  3. If letters can repeat, use current() to get the letter off the first key, then reshuffle. If letters only get used once use array_shift().
  4. After building the letter section of the string, generate a random number of appropriate range using rand()
  5. If the rand returns a low number with fewer digits than needed (like the last example) append 0’s to the start of it using the concatenation operator ( a period, PHP’s weird like that )

With some work you should be able to use that to build a program that can complete the assignment. If you have questions about the specific functions you’ll need I’ll be happy to help, but we can’t do the whole program for you.

If you do a Google (Internet) search, you can really find something that is really close to what you want.

I did that and modified a script to look like the following:

function random_num($size) {
	$alpha_key = '';
	$keys = range('A', 'Z');
	
	for ($i = 0; $i < 2; $i++) {
		$alpha_key .= $keys[array_rand($keys)];
	}
	
	$length = $size - 2;
	
	$key = '';
	$keys = range(0, 9);
	
	for ($i = 0; $i < $length; $i++) {
		$key .= $keys[array_rand($keys)];
	}
	
	return $alpha_key . $key;
}

echo random_num(9);

I’m sure if this isn’t exactly what you need it can be modified or another script can be found to fit the bill. :wink:

I’m a bit confused. The title says “unique” but you are satisfied with “random”?

Depending on how and what you’re using these for may make a difference.

For example, if they are short lived the randomness should in most cases (but not necessarily) also ensure they are unique

But if you are using them for anything non-trivial and they will be used long term, then you will want to test to see if they already exist and if they do generate another that doesn’t.

And if uniqueness is the main concern, then they might not necessarily need to be random but could also be generated sequentially.

It’s not elegant, but here is a quick and dirty case sensitive function I use for naming files:

function getName(x,y) {
    $length = rand($x,$y);
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    return $randomString;
}

The name size is variable length to help avoid collisions. Just replace $length = rand($x,$y) with a fixed length.

I’m not sure if this is what you need, just throwing out an alternative.

1 Like

Is it a good idea to append the auto-incremented id ,in the solution of pepster ?

Thank you in advance.

the autoincremented id is a unique value - so to get a unique alphanumeric key simply stick an ‘A’ on the front of the id (although there are plenty of reasons for not doing that).

random values are by definition NOT unique (unless you obtain them by shuffling an array of unique values or you test each newly generated value to check that it hasn’t been used before).

Can you please explain why you said this,

Thank you in advance.

If your unique values are sequential then it makes it really easy for someone who knows one of the values to guess the rest.

1 Like

@felgall,

Thank you for the reply,…ok that is the reason. :smile:

@felgall, how would you deal with the registration_no when the new member register in your site ? do you use random alphanumeric and append the auto-incremented id ?,because you said it’s not good to append the incremental id ?..I am confuse.

Thank you in advance.

To generate random strings I use code similar to what mawburn published in post 6. I then have a do loop where I keep calling that code until it returns a value that can’t be found in the database (generally that means that it tries to read once, gets a not found and so knows that value is currently unique and can be used). In the rare situation where a value already in use gets chosen the do loop discards the first value and generates another random value to try (which almost certainly will not be found).

This works provided that the number of values you want to use is a small fraction of the possible values you are extracting the random ones from. For example if you have 64 characters you are selecting from and randomly pick five then there are just over one billion possible values to retrieve (many more if you make the string longer - a lot fewer if you insist that certain ones be numeric).

If the number of random values you want is going to be a significant fraction of the possible random values then an alternate approach is more efficient - store all of the values in an array, shuffle the array into random order and then retrieve entries from the array sequentially - or (if you remove used values from the array) you can select them randomly without having to shuffle. Unless you have a specific maximum length then you can easily avoid this situation though simply by making the string a few characters longer.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.