PHP: Select Random Web Color with One Line of Code

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 lowest color value possible for one of these “light” sources is 0 (hex 00) and the highest value is 255 (hex FF). The color codes are written as 3 double digit numbers prefixed with a # sign. Technically, the combination of 255 x 255 x 255 possible color codes means that there exists 16 million possible colors using this particular notation.

The quickfire tip for today is the generation of a random HTML color using just a single line of PHP color. Handy if you want to throw a bit of a surprise burst of changing color here and there…

$randomcolor = '#' . strtoupper(dechex(rand(0,10000000)));

The line above will produce a value that looks something like #240BFD, perfect for slotting in any web element’s style you can think of!

Simple, wasn’t it? ;)

Related Posts:

  • 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 rem ...

  • Gradient colors are pretty awesome, pretty to look at and a nifty visual effect. Unfortunately for us though, CSS standards when it comes to handling gradients was pretty lacklustre over the years, resulting in all the major browsers pretty much defining their own browser specific CSS rules to achieve gradient ...

  • 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 required it at least once before when setting text color whilst generating PDFs using the FPDF library - so I have at least established that you do sometimes want to d ...

About Craig Lotter

South African software development manager and senior application developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

9 thoughts on “PHP: Select Random Web Color with One Line of Code

  1. Haha oops, so I did! Thanks for picking up on it Mr. Sven – I’ve fixed it appropriately. (Sigh, the amount of times I get my syntax mixed up between the various languages…)

  2. Haha oops, so I did! Thanks for picking up on it Mr. Sven – I’ve fixed it appropriately. (Sigh, the amount of times I get my syntax mixed up between the various languages…)

Leave a Reply