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— editable, runs on the server
Info

Watch a video course: Learn object oriented PHP

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