Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random hex color code with PHP

Tags:

php

hex

I'm working on a project where I need to generate an undefined number of random, hexadecimal color codes…how would I go about building such a function in PHP?

like image 221
joshdcomp Avatar asked Apr 10 '11 20:04

joshdcomp


People also ask

How do I create a hexadecimal color code?

Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers. The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue. The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB).

What hex color is 000000?

The color black with hexadecimal color code #000000 / #000 is a very dark shade of gray. In the RGB color model #000000 is comprised of 0% red, 0% green and 0% blue. In the HSL color space #000000 has a hue of 0° (degrees), 0% saturation and 0% lightness.

What color is 0xFFFFFF?

Hex Notation The smallest available color is 00 (which means 0 * 16 + 0) or 0. To tell the computer you are using a HEX number, you preceed the digits with the "0x" (zero x) notation. Thus white is generally written as 0xffffff (depending on your system capitalization may or may not matter).


1 Answers

An RGB hex string is just a number from 0x0 through 0xFFFFFF, so simply generate a number in that range and convert it to hexadecimal:

function rand_color() {     return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT); } 

or:

function rand_color() {     return sprintf('#%06X', mt_rand(0, 0xFFFFFF)); } 
like image 140
outis Avatar answered Sep 30 '22 18:09

outis