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:
-
HTML or Web colors are defined using a hexadecimal (hex) notation for the combination of Red, Green and Blue color values, commonly known as RGB. The lo ...
-
Sometimes you need to RGB array that makes up a color when working in the wonderful world of PHP. Don't ask me why or when, though that said, I have require ...
-
RGB, that annoying little way of expressing a color via values between 0 and 255 for each of the three components that makes up a color. Always in the form ...
-
Youve often seen these long, seemingly random numbers in secured web pages and perhaps wondered just what the heck that is meant to be. Well, usually these ...
-
Random posts are always fun to throw up onto your blog, as they help encourage readers stick around for that little bit longer and explore the otherwise dee ...