Generating a random hex color code with PHP
you can use md5 for that purpose,very short
$color = substr(md5(rand()), 0, 6);
An RGB hex string is just a number from 0x0 through 0xFFFFFF, so simply generate a number in that range and convert it to hexadecimal:
function rand_color() {
return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}
or:
function rand_color() {
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
Get a random number from 0 to 255, then convert it to hex:
function random_color_part() {
return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}
function random_color() {
return random_color_part() . random_color_part() . random_color_part();
}
echo random_color();
$rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT);
echo('#' . $rand);
You can change rand()
in for mt_rand()
if you want, and you can put strtoupper()
around the str_pad()
to make the random number look nicer (although it’s not required).
It works perfectly and is way simpler than all the other methods described here :)