I searched and looked for this but didn’t find a good solution online: I need to come up with a random alphanumeric string of arbitrary length **fast** and using least memory. How do you do this in PHP? Most solutions I saw posted would define a set of allowed characters, then iterate arbitrary number of times generating a random number each time that would be mapped to one of the characters. Append to result string every time and you get the result.

That method, even when done efficiently, is very expensive because:

- You have to generate a different random number with each iteration
- Use a run-time interpreted loop
- Map to character
- Append to string with every iteration

Then I thought of this:

`base_convert(mt_rand(1,pow(36,5)), 10, 36);`

What does it do?

Step 1: generates a random number between 1 and 36^5. Why 36^5? Because 36 is 26+10: 26 is for letters a-z, and 10 for numbers 0-9. base_convert function’s max base is 36. Why 5? Because for this example, I wanted to generate random string of max 5 characters in length.

Step 2: converts the resulting random number from 10-base to 36-base, resulting in a random alphanumeric string. No for-loops required.

Now, let’s take this one step further. What if we always wanted to get a result that’s n characters long? Well, creatively set a minimum for mt_rand like this:

$n = 10;

base_convert(mt_rand(base_convert(pow(10, $n-1), 36, 10), pow(36, $n)), 10, 36);

This will generate 10 character alphanumeric strings. Enjoy!

### Like this:

Like Loading...

*Related*