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?
- 3What do you mean by "web safe" exactly? The old concept of "Web safe colours" is no longer current.Pekka– Pekka2011-04-10 20:38:28 +00:00Commented Apr 10, 2011 at 20:38
- Every color has a hex code…but only certain ones are guaranteed to be rendered the same on all computers A bit of reading: bit.ly/hnFAbBjoshdcomp– joshdcomp2011-04-10 20:44:33 +00:00Commented Apr 10, 2011 at 20:44
- 3As @Pekka says, that's a very outdated concept from back when some computers only had a few hundred or thousand colours. Any computer likely to be viewing the web these days can handle millions of colours. Some reading: en.wikipedia.org/wiki/Web_colors#Web-safe_colorsceejayoz– ceejayoz2011-04-10 20:47:14 +00:00Commented Apr 10, 2011 at 20:47
- even the W3schools article you link to has it right: "This is not important today, since most computers can display millions of different colors."Pekka– Pekka2011-04-10 21:04:30 +00:00Commented Apr 10, 2011 at 21:04
- 1UPDATE: I have removed "web safe" from the question, as the OP disregarded that qualification by the accepted answer.danorton– danorton2014-03-03 03:08:33 +00:00Commented Mar 3, 2014 at 3:08
17 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)); } Comments
Get a random number from 0 to 255, then convert it to hex:
function random_color_part() { return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT); } function random_color() { return random_color_part() . random_color_part() . random_color_part(); } echo random_color(); 6 Comments
you can use md5 for that purpose,very short
$color = substr(md5(rand()), 0, 6); 2 Comments
rand() won't return a number larger than 32767 on some platforms (including Windows, as per the documentation). That aside, using md5() offers no advantages and some disadvantages over simply converting the number to hexadecimal, namely that md5() may not produce a regular distribution (some hex strings may occur more often than others).substr(md5(rand(1, 100)), 0, 6); $rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT); echo('#' . $rand); You can change rand() in for mt_rand() if you want, and you can put strtoupper() around the str_pad() to make the random number look nicer (although it’s not required).
It works perfectly and is way simpler than all the other methods described here :)
Comments
Valid hex colors can contain 0 to 9 and A to F so if we create a string with those characters and then shuffle it, we can grab the first 6 characters to create a random hex color code. An example is below!
code
echo '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6); I tested this in a while loop and generated 10,000 unique colors.
code I used to generate 10,000 unique colors:
$colors = array(); while (true) { $color = substr(str_shuffle('ABCDEF0123456789'), 0, 6); $colors[$color] = '#' . $color; if ( count($colors) == 10000 ) { echo implode(PHP_EOL, $colors); break; } } Which gave me these random colors as the result.
outis pointed out that my first example couldn't generate hexadecimals such as '4488CC' so I created a function which would be able to generate hexadecimals like that.
code
function randomHex() { $chars = 'ABCDEF0123456789'; $color = '#'; for ( $i = 0; $i < 6; $i++ ) { $color .= $chars[rand(0, strlen($chars) - 1)]; } return $color; } echo randomHex(); The second example would be better to use because it can return a lot more different results than the first example, but if you aren't going to generate a lot of color codes then the first example would work just fine.
2 Comments
range+array_merge+implode is overkill (why not simply use a string constant?). There are many potential random color strings that won't be produced as the result of str_shuffle, such as '4488CC', since each hexit occurs exactly once in the input string. You'd have to repeat each hexit exactly 6 times in the input to str_shuffle to get the correct behavior, but, at that point, it'd still be overkill.Shortest way:
echo substr(uniqid(),-6); // result: 5ebf06 1 Comment
The uniqid() function generates a unique ID based on the microtime (current time in microseconds). For those of you that wanna generate more than 1 color at a time.As of PHP 5.3, you can use openssl_random_pseudo_bytes():
$hex_string = bin2hex(openssl_random_pseudo_bytes(3)); 3 Comments
<?php foreach(range(0,100) as $n){echo("<div style='background-color:#".(bin2hex(openssl_random_pseudo_bytes(3))).";padding:1em;'></div>");}?> shows that this gives the most colourful and random results. Try it with phpfiddle.org!function random_color(){ return sprintf('#%06X', mt_rand(0, 0xFFFFFF)); } 1 Comment
Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.
See Wikipedia for more info.
In other words, use any colour from #000000 to #FFFFFF.
edit: Dear downvoters. Check the edit history for the question first.
Comments
This is heavily based on the @Galen version above, however, I wanted to add range control that could limit the colour produced to be red, green, blue, lighter or darker. It might be of use to others.
function random_colour_part($lower, $upper) { //randomly select colour in range and convert to hexidecimal return str_pad(dechex(mt_rand($lower, $upper)), 2, '0', STR_PAD_LEFT); } function random_colour($colour) { //loop through colour foreach ($colour as $key => $value) { //retrieve each r,g,b colour range and generate random hexidecimal colour if ($key == "r") $r = random_colour_part($value[0], $value[1]); if ($key == "g") $g = random_colour_part($value[0], $value[1]); if ($key == "b") $b = random_colour_part($value[0], $value[1]); } //return hexidecimal colour return "#" . $r . $g . $b; } //generate a random red-based colour echo random_colour(["r"=>[0,255], "g"=>[0,0], "b"=>[0,0]]); //generate a random light green-based colour (use only half of the 255 range) echo random_colour(["r"=>[0,0], "g"=>[127,255], "b"=>[0,0]]); //generate a random colour of any sort echo random_colour(["r"=>[0,255], "g"=>[0,255], "b"=>[0,255]]); Comments
I have noticed a comment and hereby post an answer. The old concept of Web safe colours is great. I want to remember it.
First, create inc/Palette.php
<?php class Palette { private static $items = []; /** * Direct text from https://en.wikipedia.org/wiki/Web_colors#Web-safe_colors * Copy and paste, then replace any odd space blocks with a normal space * * @return string */ private static function raw() { return "*000* 300 600 900 C00 *F00* *003* 303 603 903 C03 *F03* 006 306 606 906 C06 F06 009 309 609 909 C09 F09 00C 30C 60C 90C C0C F0C *00F* 30F 60F 90F C0F *F0F* 030 330 630 930 C30 F30 033 333 633 933 C33 F33 036 336 636 936 C36 F36 039 339 639 939 C39 F39 03C 33C 63C 93C C3C F3C 03F 33F 63F 93F C3F F3F 060 360 660 960 C60 F60 063 363 663 963 C63 F63 066 366 666 966 C66 F66 069 369 669 969 C69 F69 06C 36C 66C 96C C6C F6C 06F 36F 66F 96F C6F F6F 090 390 690 990 C90 F90 093 393 693 993 C93 F93 096 396 696 996 C96 F96 099 399 699 999 C99 F99 09C 39C 69C 99C C9C F9C 09F 39F 69F 99F C9F F9F 0C0 3C0 6C0 9C0 CC0 FC0 0C3 3C3 6C3 9C3 CC3 FC3 0C6 3C6 6C6 9C6 CC6 FC6 0C9 3C9 6C9 9C9 CC9 FC9 0CC 3CC 6CC 9CC CCC FCC 0CF 3CF 6CF 9CF CCF FCF *0F0* 3F0 *6F0* 9F0 CF0 *FF0* 0F3 *3F3* *6F3* 9F3 CF3 *FF3* *0F6* *3F6* 6F6 9F6 *CF6* *FF6* 0F9 3F9 6F9 9F9 CF9 FF9 *0FC* *3FC* 6FC 9FC CFC FFC *0FF* *3FF* *6FF* 9FF CFF *FFF*"; } public static function webSafeColors() { if (empty(self::$items)) { self::$items = explode(' ', str_replace(['*', "\n"], ['', ' '], self::raw())); } return self::$items; } public static function randomColor() { $colors = self::webSafeColors(); $count = count($colors); return '#' . $colors[rand(0, $count - 1)]; } } In somewhere include this file like:
include __DIR__ . '/../inc/Palette.php'; // dump the result var_dump(Palette::randomColor()); Comments
you can use
function getRandomColor() { $letters = '0123456789ABCDEF'; $color = '#'; for ($i = 0; $i < 6; $i++) { $color .= $letters[rand(0, 15)]; } return $color; }