I am looking for the shortest way to generate random/unique strings and for that I was using the following two:
$cClass = sha1(time());
or
$cClass = md5(time());
However, I need the string to begin with an an alphabet character, I was looking at base64 encoding but that adds ==
at the end and then I would need to get rid of that.
What would be the best way to achieve this with one line of code?
Update:
PRNDL came up with a good suggestions wich I ended up using it but a bit modified
echo substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31)
Would yield 32 characters mimicking the md5 hash but it would always product the first char an alphabet letter, like so;
However, Uours really improved upon and his answer;
substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);
is shorter and sweeter
The other suggestion by Anonymous2011 was very awesome but the first character for some reason would always either M, N, Y, Z so didnt fit my purposes but would have been the chosen answer, btw does anyone know why it would always yield those particular letters?
Here is the preview of my modified version
echo rtrim(base64_encode(md5(microtime())),"=");
Rather than shuffling the alphabet string , it is quicker to get a single random char .
Get a single random char from the string and then append the
md5( time( ) )
to it . Before appendingmd5( time( ) )
remove one char from it so as to keep the resulting string length to 32 chars :Lowercase version :
Or even shorter and a tiny bit faster lowercase version :
A note to anyone trying to generate many random strings within a second:
Since
time( )
returns time in seconds ,md5( time( ) )
will be same throughout a given second-of-time due to which if many random strings were generated within a second-of-time, those probably could end up having some duplicates .I have tested using below code . This tests lower case version :
I have generated this code for you. Simple, short and (resonably) elegant.
This uses the base64 as you mentioned, if length is not important to you - However it removes the "==" using str_replace.
I'm using this one to generate dozens of unique strings in a single go, without repeating them, based on other good examples above:
This way, I was able to generate 1.000.000 unique strings in ~5 seconds. It's not THAT fast, I know, but as I just need a handful of them, I'm ok with it. By the way, generating 10 strings took less than 0.0001 ms.
I had found something like this:
base_convert(microtime(true), 10, 36);
JavaScript Solution:
Reference URL : Generate random string using JavaScript
PHP Solution:
Reference URL : Generate random String using PHP