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.– PekkaApr 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/hnFAbB– joshdcompApr 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_colors– ceejayozApr 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."– PekkaApr 10, 2011 at 21:04
-
1UPDATE: I have removed "web safe" from the question, as the OP disregarded that qualification by the accepted answer.– danortonMar 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));
}
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();
-
9Actually this method is the slowest of all the answers, the last 2 answers are 300% faster ( I tested it generating and outputting 2500 table cells );– aleationApr 10, 2013 at 15:37
-
1
-
4@aleation - 300% faster than .005 seconds! great! Seriously though, use whatever is the most readable. Don't nit pick over .00007 seconds. (not saying mine is most readable)– GalenJun 26, 2013 at 16:32
-
1@aleation: Galen is right in why I still have his answer marked as the accepted solution. While things are more efficient below, I can leave the above code as-is and people will understand what I'm doing. Not so much for the oneliners below. Oct 24, 2014 at 1:45
-
whether this is more readable or not depends on the person who reads it. I find it much more readable not having to wrap my head around two functions and a one-lines is much more flexible in its application. With this I can do eg <?= '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT); ?> Mar 17, 2018 at 9:27
you can use md5 for that purpose,very short
$color = substr(md5(rand()), 0, 6);
-
11Without an argument,
rand()
won't return a number larger than 32767 on some platforms (including Windows, as per the documentation). That aside, usingmd5()
offers no advantages and some disadvantages over simply converting the number to hexadecimal, namely thatmd5()
may not produce a regular distribution (some hex strings may occur more often than others).– outisJun 6, 2013 at 19:36 -
$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 :)
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.
-
The
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 ofstr_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 tostr_shuffle
to get the correct behavior, but, at that point, it'd still be overkill.– outisDec 14, 2015 at 0:59 -
I agree that the ranges, merge and implode was overkill and replaced them with a simple string of characters. I did think of hexadecimals such as '4488CC' but I wanted to keep it simple in 1 line of code without the line getting very long. I created a function which could generate hexadecimals such as '4488CC' I'll add it to my answer.– TURTLEDec 26, 2015 at 18:03
Shortest way:
echo substr(uniqid(),-6); // result: 5ebf06
-
5This wont work for more than 1 color, as the time will be the same, so will the uniqid().
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. Feb 19, 2017 at 11:39
If someone wants to generate light colors
sprintf('#%06X', mt_rand(0xFF9999, 0xFFFF00));
This is how i do it.
<?php echo 'rgba('.rand(0,255).', '.rand(0,255).', '.rand(0,255).', 0.73)'; ?>
As of PHP 5.3, you can use openssl_random_pseudo_bytes():
$hex_string = bin2hex(openssl_random_pseudo_bytes(3));
-
2
-
2@TimWolla: I'm not sure what you mean by "overkill", but note: 1) There is nothing in the question that indicates the purpose or how "random" the number is to be, and 2) In my tests, the answer I proposed runs considerably faster than the accepted answer. 3) Instead of creating two functions as with the accepted answer, my answer is a single line of code.– danortonMar 3, 2014 at 2:37
-
<?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!– Berry M.Oct 31, 2017 at 15:19
function random_color(){
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
-
2
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.
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]]);
I think this would be good as well it gets any color available
$color= substr(str_shuffle('AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899'), 0, 6);
function randomRGB()
{
$r = rand(0, 255);
$g = rand(0, 255);
$b = rand(0, 255);
return "rgb({$r}, {$g}, {$b})";
}
function randomHexColor()
{
return '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);
}
$hexColor = randomHexColor();
$rgbColor = randomRGB();
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());
you can use
function getRandomColor()
{
$letters = '0123456789ABCDEF';
$color = '#';
for ($i = 0; $i < 6; $i++) {
$color .= $letters[rand(0, 15)];
}
return $color;
}