开发者

PHP rand generating zeros even though range is supposed to be 2 to 36?

for ($i = 1; $i <= $numITER; $i++) {
    $val = rand(2,36);

    switch (TRUE) {
        case ($val<=10):
            $vercodeTEMP.=$val;
            break;
        case ($val>10):
            if ($val != 25 && $val != 19) {
                $vercodeTEMP.=chr(54+$val);
            } else {
                $i=$i-1;
            }
            break;
    }
}

I'm basically trying to avoid 0, 1, and the letters O and I. How can this poss开发者_运维技巧ibly be giving me zero's when the rand range is 2 to 36?


If $val == 10, then you will append $val onto $vercodeTEMP.

Try:

for ($i = 1; $i <= $numITER; $i++) {
    $val = rand(2,36);

    if ($val<10) {
        $vercodeTEMP.=$val;
    } else if ($val != 25 && $val != 19) {
        $vercodeTEMP.=chr(54+$val);
    } else {
        $i=$i-1;
    }
}


I'm basically trying to avoid 0, 1, and the letters O and I

What about not messing with magic numbers (besides position) and using PHP's range()?

$numbers = range(2, 9);
$letters = range('a', 'z');
unset($letters[8], $letters[14]);
$letters = array_merge($letters, array_map('strtoupper', $letters));

$pool = array_merge($numbers, $letters);

shuffle($pool);

$captcha = join(array_slice($pool, 0, $numITER)); // e.g. 2ESQcnMTNy

CodePad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜