I\'m trying to generate random HTML colors in PHP, but I\'m having trouble getting them to look similar, or in the same family. Is there some function I can use to generate
function randomColor() {
$str = '#';
for ($i = 0; $i < 6; $i++) {
$randNum = rand(0, 15);
switch ($randNum) {
case 10: $randNum = 'A';
break;
case 11: $randNum = 'B';
break;
case 12: $randNum = 'C';
break;
case 13: $randNum = 'D';
break;
case 14: $randNum = 'E';
break;
case 15: $randNum = 'F';
break;
}
$str .= $randNum;
}
return $str;}
Try this:
//For every hex code
$random = mt_rand(0, 16777215);
$color = "#" . dechex($random);
And than you can just use it like this:
background-color: <?php echo $color ?>;
I'd just limit the range of the rand()-params:
// full color palette (32 bit)
for($index = 0; $index < 30; $index++)
{
echo '<div style="background-color: #' . dechex(rand(0,16777215)) . '; display: inline-block; width: 50px; height: 50px;"></div>';
}
echo '<br />';
// pastell colors
for($index = 0; $index < 30; $index++)
{
echo '<div style="background-color: rgb(' . rand(128,255) . ',' . rand(128,255) . ',' . rand(128,255) . '); display: inline-block; width: 50px; height: 50px;"></div>';
}
echo '<br />';
// dark colors
for($index = 0; $index < 30; $index++)
{
echo '<div style="background-color: rgb(' . rand(0,128) . ',' . rand(0,128) . ',' . rand(0,128) . '); display: inline-block; width: 50px; height: 50px;"></div>';
}
echo '<br />';
// shades of blue
for($index = 0; $index < 30; $index++)
{
echo '<div style="background-color: rgb(' . rand(0,56) . ',' . rand(0,56) . ',' . rand(0,255) . '); display: inline-block; width: 50px; height: 50px;"></div>';
}
echo '<br />';
// shades of green
for($index = 0; $index < 30; $index++)
{
echo '<div style="background-color: rgb(' . rand(0,56) . ',' . rand(0,255) . ',' . rand(0,56) . '); display: inline-block; width: 50px; height: 50px;"></div>';
}
echo '<br />';
// shades of red
for($index = 0; $index < 30; $index++)
{
echo '<div style="background-color: rgb(' . rand(0,255) . ',' . rand(0,56) . ',' . rand(0,56) . '); display: inline-block; width: 50px; height: 50px;"></div>';
}
RandomColor has been ported to PHP, you can find it here. With it it's also possible to have random light or random dark colors.
Example Usage:
include('RandomColor.php');
use \Colors\RandomColor;
// Returns a hex code for a 'truly random' color
RandomColor::one(array(
'luminosity' => 'random',
'hue' => 'random'
));
// Returns a hex code for a light blue
RandomColor::one(array(
'luminosity' => 'light',
'hue' => 'blue'
));
A few years ago I came across this class. It lets you generate complimentary colors based on a seed value.
If you're looking for something more general, limit yourself to a general range using rand
(obviously below 255) and the use base_convert.
Found something much nicer posted on the blog of someone called Craig Lotter:
$randomcolor = '#' . dechex(rand(0,10000000));