Generate random hex color with PHP

Josh Sherman
1 min read
Software Development PHP

There’s many ways to skin a cat, or generate a color. You could randomize a number between 0 and 16777215 then convert it to hex:

$rand_color = '#' . dechex(mt_rant(0, 16777215));

Or you could do what I like to do, just md5 a random string and grab the first 6 characters:

$rand_color = '#' . substr(md5(mt_rand()), 0, 6);

As it turns out, they are the same number of keystrokes but my preferred method includes 3 function calls instead of 2. Seriously though, it’s your call :P

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Slobberknocker: My Life in Wrestling
The 4-Hour Workweek, Expanded and Updated

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles