Tools
- Sandbox
- Paste Code
- Snippets
- Generators
- Checks
- Convertors
How to generate random hex color in PHP
Snippet
Share
Do you find this snippet useful? Then share it with your friends or colleagues. This will help us to make our free web tools better.
First version:
<?php
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
$color = '#'.$rand[mt_rand(0,15)].$rand[mt_rand(0,15)].$rand[mt_rand(0,15)].$rand[mt_rand(0,15)].$rand[mt_rand(0,15)].$rand[mt_rand(0,15)];
echo $color;
?>
<body style="background: <?=$color;?>;">
Then echo out the $color
value anywhere you need it. For example:
<body style="background: <?=$color;?>;">
Second(short) version:
<?php
printf( "#%06X\n", mt_rand( 0, 0xFFFFFF ));