Skip to content
Advertisement

Generating a random hex color code with PHP

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:

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();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement