I m using following code to get random hex values. But the output is inconsistent Sometimes it returns 6 digits sometimes 5 digits
function generateHexValue($length=6)
{
$chars = "0123456789abcdef";
$i = 0;
$str = "";
while ($i<$length) {
$str .= $chars[mt_rand(0,strlen($chars))];
$i++;
}
return $str;
}
$col=generateHexValue();
echo "<div style='background-color:#".$col."; width:100px; height:100px;'></div>";
echo $col."<br/>";
Your call to mt_rand() should have a max of strlen($chars)-1, not strlen($chars). The max of mt_rand is inclusive. You could get an index off the end of $chars array (e.g. $chars[16], which is an undefined offset into $chars). Not sure what PHP would make of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With