随机字符串生成器返回相同的值

时间:2013-12-12 18:42:56

标签: php

$list_ar = array();
for($x = 0;$x < 500; $x++){
    $val = generateRandomString(20);
    if(!in_array($val,$list_ar)){
        echo $x.'=='.$val.'<br>';
        array_push($list_ar,$val);
    } else {
        echo $x.'== IN ARRAY<br>';
    }
}

function generateRandomString($length){
    $characterlist = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
    $characterlist_array = str_split($characterlist);
    $id = '';
    for($a = 0;$a<$length;$a++){
        shuffle($characterlist_array);
        $position = array_rand($characterlist_array, 1);
        $id .= $characterlist_array[$position];
    }
    return $id; 
}

当我运行上面的代码时,它会向 in array false 提供 360 lines ,然后返回 in array true < / strong>即可。我希望它在数组中返回false,直到 500 lines 我已经运行了20多次代码并且它给出了与 {{1}相同的结果} 即可。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

根据Marc的说法,如果将功能更改为:

,会发生什么
function generateRandomString($length){
    $characterlist = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
    $characterlist_count = strlen($characterlist)-1;

    $id = '';
    for($a = 0;$a<$length;$a++){
        $id .= $characterlist[rand(0,$characterlist_count)];
    }
    return $id; 
}

它还会失败吗?

答案 1 :(得分:0)

因为我们正在回答替代方案:

function generateRandomString($length) {
    $characterlist = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
    $characterlist_array = str_split($characterlist);
    shuffle($characterlist_array);

    return implode(array_slice($characterlist_array, 0, $length));
}