Generate a random RGB or Hex color using PHP.

In this tutorial, we are going to show you how to generate a random RGB or Hex color using PHP.

An RGB color consists of three numerical values.

These values represent Red (R), Green (G) and Blue (B). Furthermore, 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 above, you will see that it creates an array containing three randomly generated RGB values.

In order to use this random color, you can join the three array values together and then print them out onto the page.

For example, let’s say that you want to create a random background color for a DIV element:

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

If you run the code above and refresh your web page, you’ll see that it changes each time.

Converting RGB to Hex using PHP.

If you’re a web developer or designer, then you’re probably more comfortable using Hex colors than RGB.

To generate a random Hex color with PHP, we will need to convert our 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 integer into its hexadecimal representation.

This is a custom function that you can copy into your project:

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();

The function above will generate a random color in both formats and then return it in an array.