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:


$rgbColor = array();

//Create a loop.
foreach(array('r', 'g', 'b') as $color){
    //Generate a random number between 0 and 255.
    $rgbColor[$color] = mt_rand(0, 255);


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:

<div style="background-color: rgb(<?= implode(",", $rgbColor); ?>);">
    Random Color!

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:


$hex = '#';

//Create a loop.
foreach(array('r', 'g', 'b') as $color){
    //Random number between 0 and 255.
    $val = mt_rand(0, 255);
    //Convert the random number into a Hex value.
    $dechex = dechex($val);
    //Pad with a 0 if length is less than 2.
    if(strlen($dechex) < 2){
        $dechex = "0" . $dechex;
    $hex .= $dechex;

//Print out our random hex color.
echo $hex;

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:


function randomColor(){
    $result = array('rgb' => '', 'hex' => '');
    foreach(array('r', 'b', 'g') as $col){
        $rand = mt_rand(0, 255);
        $result['rgb'][$col] = $rand;
        $dechex = dechex($rand);
        if(strlen($dechex) < 2){
            $dechex = '0' . $dechex;
        $result['hex'] .= $dechex;
    return $result;

$myColor = randomColor();

Hopefully, you will find it useful! Enjoy!