Generating a random hex color code with PHP

joshdcomp picture joshdcomp · Apr 10, 2011 · Viewed 119.7k times · Source

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?

Answer

outis picture outis · Mar 28, 2012

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));
}