PHP: Random Color Generator Function CodeUnit 20 OCT 2010

Although I’ve posted simple random color generating code snippets before, I’ve noticed since that most of them have a flaw in that they sometimes don’t always produce a proper six character long hex color code.

Hence I have posted my latest random color generating PHP function to these pages in the interest of reminding myself at a later stage when I need it again!

So let’s have a look at the function shall we?

function generateRandomColor(){
    $randomcolor = '#' . strtoupper(dechex(rand(0,10000000)));
    if (strlen($randomcolor) != 7){
        $randomcolor = str_pad($randomcolor, 10, '0', STR_PAD_RIGHT);
        $randomcolor = substr($randomcolor,0,7);
    }
return $randomcolor;
}

Pretty simple really.

Grab a random decimal number, convert it to hex and pad right with some zeroes to ensure the proper character length.

Fairly random and guaranteed to always give you pretty results!

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Tim

    This is a great function, just what I was looking for, thank you.

  • Paweł Trauth

    shouldn’t the seed be 16777216?