# 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.

- <?php
- /**
- * Get random color hex value
- *
- * @param int $max_r Maximum value for the red color
- * @param int $max_g Maximum value for the green color
- * @param int $max_b Maximum value for the blue color
- * @return string
- */
- function getRandomColorHex($max_r = 255, $max_g = 255, $max_b = 255)
- {
- // ensure that values are in the range between 0 and 255
- $max_r = max(0, min($max_r, 255));
- $max_g = max(0, min($max_g, 255));
- $max_b = max(0, min($max_b, 255));
- // generate and return the random color
- return str_pad(dechex(rand(0, $max_r)), 2, '0', STR_PAD_LEFT) .
- str_pad(dechex(rand(0, $max_g)), 2, '0', STR_PAD_LEFT) .
- str_pad(dechex(rand(0, $max_b)), 2, '0', STR_PAD_LEFT);
- }

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!

1

2

3

4

5

6

7

8

9