W3docs

Generating a random hex color code with PHP

You can use the dechex function in PHP to convert a random number to a hexadecimal value, and then use that value as a color code.

You can use random_int() to generate a random number and sprintf() to format it as a zero-padded hexadecimal value, and then use that value as a color code. For example:

Example of generating a random hex color code with PHP

<?php

$color = sprintf('%06x', random_int(0, 0xFFFFFF));
echo $color;

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This will generate a random hex color code between the values of 000000 and FFFFFF, which represents the full range of possible colors.