PHP function that generates a random hexadecimal color code

Rumman Ansari   2023-03-03   Developer   web development > color code   201 Share

Here's an example PHP function that generates a random hexadecimal color code:


function randomColor() {
  $color = '#';
  $color .= str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT); //red
  $color .= str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT); //green
  $color .= str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT); //blue
  return $color;
}

This function generates a random 6-digit hexadecimal color code by concatenating the hexadecimal values of red, green, and blue components. The mt_rand() function is used to generate a random number between 0 and 255, and dechex() function is used to convert the number to a two-digit hexadecimal value. The str_pad() function is used to ensure that each component has two digits, adding leading zeros if necessary.

You can call this function like this:


$color = randomColor();
echo $color;

This will output a random color code like "#3e7ab3".