Generate random HEX color value

Ever needed to generate a random HEX color value? Here is a function for those rare times you might need it.

  1. <?php
  2.  
  3. /**
  4.  * Get random color hex value
  5.  *
  6.  * @param  int $max_r Maximum value for the red color
  7.  * @param  int $max_g Maximum value for the green color
  8.  * @param  int $max_b Maximum value for the blue color
  9.  * @return string
  10.  */
  11. function getRandomColorHex($max_r = 255, $max_g = 255, $max_b = 255)
  12. {
  13.     // ensure that values are in the range between 0 and 255
  14.     $max_r = max(0, min($max_r, 255));
  15.     $max_g = max(0, min($max_g, 255));
  16.     $max_b = max(0, min($max_b, 255));
  17.    
  18.     // generate and return the random color
  19.     return str_pad(dechex(rand(0, $max_r)), 2, '0', STR_PAD_LEFT) .
  20.            str_pad(dechex(rand(0, $max_g)), 2, '0', STR_PAD_LEFT) .
  21.            str_pad(dechex(rand(0, $max_b)), 2, '0', STR_PAD_LEFT);
  22. }

As you can see, it is using PHP's built-in dechex function, which converts decimal number to a hex value. We get random hex values between 0 and 255 for each of the colors, concatenate them together and prepend the hash sign. As easy as that!

Comments
1
Whilst this works, it will often generate a hex string which is only 4 or 5 characters long resulting in 'white' more often than not.

To remedy this I did a simple check using strlen() and then generated an additional 1 or 2 digits depending on the length like so:

$hexa = dechex(rand(0,  255)) . dechex(rand(0,  255)) . dechex(rand(0,  255));
if( strlen( $hexa ) == 4 )
{
    $hexa = $hexa . rand(10,99);
}
else if( strlen( $hexa ) == 5 )
{
    $hexa = $hexa . rand(0,9);
}

return '#' . $hexa;

You could add onto this further so it generates an additional 1 or 2 characters rather than digits if you wanted, but I not getting a lot of 'white' colours any more ;)
Dan, March 21st 2010, 14:16
2
You are not using your maximum values to generate the components, the minimum and maximum are hard-coded. Also, as Dan has pointed out, this generates short strings sometimes - statistically about 17.6% of the time. This can be fixed by padding each value. Or if you're not changing the upper bound of each component, just generate six random values between 0 and 15 instead.

Change line 22 to this:
return '#' . component(max_r) . component(max_g) . component(max_b);

And add this function:

function component($max)
{
    return str_pad(dechex(rand(0,$max)),2,'0',STR_PAD_LEFT);
}

Et voila.
Duncan, November 17th 2010, 4:04
3
You are absolutely right, Duncan! I don't know how I missed that...
Function is now fixed and uses the padding to always have a string of 6 characters.
Thanks for pointing that out!
Andris, November 26th 2010, 15:52
4
Also,
function getRandomColorHex($max_r = 255, $max_g = 255, $max_b = 255) {
return sprintf( '#%02X%02X%02X', rand(0,$max_r), rand(0,$max_g), rand(0,$max_b) );
}
jmhobbs, September 26th 2011, 21:24
5
In the lines that read -> 
str_pad(dechex(rand(0, $max_r))), 2, '0', STR_PAD_LEFT)

The bracket is in the wrong place, after the $max_r.  It should read:

str_pad(dechex(rand(0, $max_r)), 2, '0', STR_PAD_LEFT)

Do the same for all 3 lines.
Bjern Potgieter, March 21st 2012, 9:17
6
Thanks, Bjern! Removed the extra bracket.
Andris, March 23rd 2012, 13:56
7
This may be off topic, because it looks like you're generating an RGB code, not a hex triplet, but i found another piece of code that was close - but didn't work. Here's what I've come up with:


function colorRan(){
  $letters = "1234567890ABCDEF";
  while(strlen($str)<6){
    $pos = rand(1,16);
    $str .= $letters{$pos};
  }
  return "#".$str;
}
Josh, June 13th 2012, 19:54
8
It's a rare case but I needed it. Thanks.
Devy, November 29th 2012, 11:35
9
Nice share. It's really helpful. I've a case that really need to generate a random colors in hex format. Thanks.
Mochamad Gufron, August 17th 2013, 0:54
Name
Email (required)
will not be published
Website
Recaptcha
you will only be required to fill it in once in this session

You can use [code][/code] tags in your comments