So I was wonder what are some good/preferred methods for generating a ‘hex-like’ value in PHP? Preferably, I would want to restrict it to 5 characters long like such: 1e1f7
Currently this is what I am doing:
echo dechex(mt_rand(10000, 99999));
however this gives me values anywhere from 4-5 characters long, and I want to keep it at a consistent 4 or 5.
What are some ways to better generate something like this in PHP? Is there even a built in function?
Note: When I say ‘hex-like’ I really just mean a random combination of letters and numbers. There does not have to be a restriction on available letters.
Something simple like:
(untested)
Or fix your
mt_randrange to:mt_rand(65535, 1048575)(10000-fffff in hex) or if you like tinfoil hats:mt_rand(hexdec("10000"), hexdec("ffffff"))The advantage of the while-loop approach is that it works for arbitrarily long strings. If you’d want 32 random characters you’re well over the integer limit and a single
mt_randwill not work.If you really just want random stuff, I’d propose:
(untested)