Search This Blog

Wednesday, October 13

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

 <?php

$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.

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:

<?php

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

echo '<div style="width: 100px; height: 100px;background-color: '.$rand_color.'; ?>;"></div>';

?>

One response to “Generating random CSS hex color code using PHP md5() function”

No comments:

Post a Comment