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?
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).
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.
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).
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)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With