How to Get Random Colors

Depending on the color format, there are different ways of getting a random color.

For a random RGB color, we would need three numbers between 0 - 255, and for a color, in the HSL format, we need one number between 0 - 360 and two numbers between 0 - 100.

If we want a random HEX color, we would need a number between 0 - 16777215, which we then convert from decimal to hexadecimal.

RGB

The PHP code for a random RGB color would look like this:

<?php
  echo 'rgb(' . rand(0, 255) . ', ' . rand(0, 255) . ', ' . rand(0, 255) . ');';
📋 Copy Code

In Javascript, the Math.random returns a number between 0 - 1, so we need to multiply this number by 255 to get random numbers between 0 - 255.


    alert('rgb(' + Math.floor((Math.random()  255)) + ', ' + Math.floor((Math.random()  255)) + ', ' + Math.floor((Math.random() * 255)) + ');');
📋 Copy Code

HSL

In PHP we can get a random HSL color just like this:

<?php 
  echo 'hsl(' . rand(0, 360) . ', ' . rand(0, 100) . '%, ' . rand(0, 100) . '%);';
📋 Copy Code

In Javascript, we need to multiply the return value from Math.random again this time with 360 for the first number and 100 for the following numbers.


    alert('hsl(' + Math.floor((Math.random()  360)) + ', ' + Math.floor((Math.random()  100)) + '%, ' + Math.floor((Math.random() * 100)) + '%);');
📋 Copy Code

HEX

To get a random HEX color in PHP, we first create a random number between 0 - 16777215 (0xFFFFFF) with mt_rand, and then we convert this decimal number in a hexadecimal one.

As a HEX color always needs 3 or 6 digits, we will need to pad the string to a six-digit hex value with str_pad.

<?php
  echo '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
📋 Copy Code

For a better overview I split up the Javascript code in multiple lines:


    var randomNumber = Math.floor((Math.random() * 16777215));
    var randomHex    = randomNumber.toString(16);
    var randomHexColor = randomHex.padStart(6, 0);
    alert('#' + randomHexColor);
📋 Copy Code