I just wrote a random number generator in PHP how do you think this can be improved? [closed]
-
23-06-2021 - |
Pregunta
I was working for a client and he wanted codes generated in the format [char][int][int] like in T56, N78, J89, etc... The char has to be in upper case.
As a quickie I wrote this function as I found it the simplest
function randomizer(){
$chars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
return $chars[array_rand($chars)].mt_rand(10, 99);
}
But I kept on wondering that there will be many other efficient solutions. This one above just works, but I am looking more towards efficiency as I need to generate loads of such Codes.
What better place to start!
Solución
echo chr(mt_rand(65,90)).str_pad((rand()%100),2,0,STR_PAD_LEFT);
Otros consejos
You'd want to store $chars
outside of the function if you can, so it doesn't need to be created every time (if you wanted to generate 1000 codes in a loop for example).
Also, here is a shortcut for you
$chars = range("A","Z");
function getRandStr()
{
return sprintf("%s%02d", chr(mt_rand(65, 90)), mt_rand(0, 99));
}
EDIT: Changed according to comment, thanks @DaveRandom.