Generating random CSS hex color code using PHP md5() function

By Faruque Ahamed Mollick

In this post, we are going to see how to generate random CSS hex color code using the PHP md5() function.

The PHP md5() function calculates the MD5 hash of a string. Using this function we are now going to generate our random hex color code.

It is just one line of code that will generate the random hex color in PHP. Below is the given PHP code that will generate the random hex color code:


$rand_color = "#".substr(md5(rand()), 0, 6);

echo $rand_color;


In the above code, we have taken the PHP rand() function which will generate random integer. We have created the MD5 hash of the random number that is generating by PHP rand() function. After that, we have used the PHP substr() function that takes only first 6 characters of the MD5 hash.

How To Display A Random Image From Directory In PHP?

Reading A Text File Line By Line In Java With Example

We have taken only first 6 characters as the hex color code built in 6 characters only except the “#”. We have taken the “#” before the character generated by substr() PHP function.

In the above code, we will only be able to see the color code string. But we will not understand what is the color or what the color looks like. So we are going to create a div element and set a background color to that element.

Below is our code where we will understand how the color looks generated randomly in PHP using md5() function:

$rand_color = "#".substr(md5(rand()), 0, 6);
echo '<div style="width: 100px; height: 100px;background-color: '.$rand_color.'; ?>;"></div>';


Leave a Reply

Your email address will not be published. Required fields are marked *