Amarjeet Hans
Amarjeet Hans

Reputation: 61

Total digits are inconsistent

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/>";

Upvotes: 2

Views: 72

Answers (3)

Ravi
Ravi

Reputation: 737

substr(md5(mt_rand()), 0, 6) does the same thing but faster.

Upvotes: -2

Nick Shaw
Nick Shaw

Reputation: 2113

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.

Upvotes: 6

deceze
deceze

Reputation: 522480

That's because mt_rand(0,strlen($chars)) returns a number between 0 and 16 (inclusive), but your $chars string only has the offsets 0 - 15. A classic off-by-one mistake.

Upvotes: 5

Related Questions