Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total digits are inconsistent

Tags:

php

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/>";
like image 773
Amarjeet Hans Avatar asked Jan 17 '26 22:01

Amarjeet Hans


1 Answers

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.

like image 67
Nick Shaw Avatar answered Jan 19 '26 17:01

Nick Shaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!