Search code examples
phpperformanceprocessing-efficiencymemory-efficient

I just wrote a random number generator in PHP how do you think this can be improved?


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!


Solution

  • echo chr(mt_rand(65,90)).str_pad((rand()%100),2,0,STR_PAD_LEFT);