Forum Moderators: coopster
Try not to generate more than a thousand or so. Each new color needs to be compared to all previous colors so the processing time increases exponentially. Maybe quadratically? Or factorially? I don't know, it just gets slower and slower. ;)
<?php
function generateUniqueHexColors($quantity=10){
if($quantity >= (254*254*254)){ // Don't try to generate the full set of hex colors this way.
return false;
}
$colors = array();
$quantity = (intval($quantity) == 0)? 1 : intval($quantity);
for($i=0; $i<$quantity; $i++){
$color = sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
while( in_array($color, $colors) ){
//echo $i.': '.$color.' already existed<br />'; // uncomment to debug
$color = sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
}
$colors[] = $color;
}
return $colors;
}
$colors = generateUniqueHexColors(1000); // anything over 1000 is rather slow
/*/ To test that it worked:
$unique = array_unique($colors);
if( $colors!= $unique ){ echo '<h1>Failed!</h1>'; } else { echo '<h1>Success!</h1>'; }
print_r($colors);
// */
echo '<style type="text/css">div.b { width: 20px; height: 20px; float:left; }</style>';
foreach($colors as $c=>$v){
echo '<div style="background-color: #'.$v.'" class="b"></div>';
}
?>