PHP: Select Random Web Color with One Line of Code CodeUnit 17 APR 2010

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:

About Craig Lotter

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

  • http://blog.sven.co.za/ Sven Welzel

    Quick heads-up: Surely you meant strtoupper for this PHP example (rather than the VB script ucase that would use the & as concatenation character…?
    .-= Sven Welzel´s last blog ..Windows cannot find FILENAME from Outlook or Thunderbird – Make sure you typed the name correctly, and then try again. =-.

  • http://blog.sven.co.za Sven Welzel

    Quick heads-up: Surely you meant strtoupper for this PHP example (rather than the VB script ucase that would use the & as concatenation character…?
    .-= Sven Welzel´s last blog ..Windows cannot find FILENAME from Outlook or Thunderbird – Make sure you typed the name correctly, and then try again. =-.

  • http://www.craiglotter.co.za Craig Lotter

    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…)

  • http://www.craiglotter.co.za Craig Lotter

    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…)

  • http://web2clone.com/ Saroj

    nice, Thanks

  • Scott Rowley

    Exactly what I was looking for.  thanks!

    • http://www.craiglotter.co.za Craig Lotter

      Excellent, glad I could assist! :)

  • Tijo

    super

  • Sale

    Great blog, thanks for the tip!