Generate a random RGB or Hex color in PHP.

This is a simple tutorial on how to generate a random RGB or Hex color in PHP.

An RGB color is made up of three numerical values. These values represent Red (R), Green (G) and Blue (B). These numbers can range between 0 and 255.

That means that we can generate a random RGB value like so:

If you run the PHP code snippet above, you’ll get an associative array (with three elements) that contains a randomly generated RGB value. Simply join the three array values together and you’ll have a random RGB color that you can print out onto a web page. Below, I’ve assigned these random RGB values as the background color for a DIV element:

But what if you want a random Hex color (the color format of choice for HTML / CSS)?

Converting RGB to Hex.

To generate a random Hex color with PHP, we will need to learn how to convert RGB values into their corresponding Hex values.

To do this, we can use the function dechex, which converts decimal values into hexadecimal:

As you can see, we simply extended the logic in our first example by converting the random numerical value that we generated with mt_rand.

Here’s a custom function that I created. It generates a random color in both formats before returning an associative array:

Hopefully, you will find it useful! Enjoy!