PHP: Random Color Generator Function

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!

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , . Bookmark the permalink.
    blog comments powered by Disqus