generate random unique hex color code using PHP

generate random unique hex color code using PHP

echo '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);

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

In this post, we are going to see how to generate random CSS hex color codes using 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.

Generate random CSS hex color code using PHP md5() function with simple example code and apply it to a div element to change the background color of this element.

It’s just one line of code that will generate random hex colors in PHP. Below is the PHP code that will generate random hex color codes:

random unique hex color

<?php

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

echo $rand_color;

?>

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

We have taken only first 6 characters as hex color code which is made into 6 characters except “#”. We have taken “#” before the character generated by substr() PHP function.
Below is our code where we will understand how color is generated randomly in PHP using md5() function:

random unique hex color

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

Generating random CSS hex color code using PHP

Scroll to Top