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?
Advertisement
Answer
Get a random number from 0 to 255, then convert it to hex:
JavaScript
x
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();