I\'m working on a project where I need to generate an undefined number of random, hexadecimal color codes…how would I go about building such a function in PHP?
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));
}
Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.
See Wikipedia for more info.
In other words, use any colour from #000000 to #FFFFFF.
edit: Dear downvoters. Check the edit history for the question first.
$color = sprintf("#%06x",rand(0,16777215));
$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 :)
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();
you can use md5 for that purpose,very short
$color = substr(md5(rand()), 0, 6);