2

这是我的代码

<?php

function random_id() {
    $chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $id = '';
    for ($i = 0; $i < 5; ++$i)
    {
        $id .= $chars[rand(1, 26)];
    }
    echo $id;
}

random_id();

?>

它不断生成带有 5 个小写数字的 ID,并且非常偶尔会在其中包含一个数字。我也尝试过mt_rand(),并且还在循环之前的脚本开头使用srand(time())and 。srand(microtime())

另外,应该是rand(1, 26)还是rand(0, 25)

4

6 回答 6

8

您的字符串长度超过 26 个字符。请改用此 rand 函数:

rand(0, strlen($chars) - 1)

因此,您不必在每次迭代时计算字符串长度,但仍保持动态,值得考虑将计算移到循环之外,如下所示:

$chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$chars_cnt = strlen($chars) - 1;
for ($i = 0; $i < 5; ++$i)
{
    $id .= $chars[rand(1, $chars_cnt)];
}
于 2013-01-20T17:09:05.460 回答
4

您没有生成足够高的随机数来获取整个数组。

小写字符:0-25

号码:26-35

大写汽车:36-61

于 2013-01-20T17:09:13.770 回答
2

0 is the start point and strlen($chars) is the count of character in the $str string.

You should change your code to this:

    for ($i = 0; $i < 5; ++$i)
    {
        $id .= $chars[rand(0, strlen($chars)-1)];
    }
于 2013-01-20T17:11:54.427 回答
1

I think you need to remember to use a bigger number than 26, as that is the number of letters in the alphabet, you might want to use 26+26+10= 62:

$id .= $chars[rand(0, 61)];

CHEERS!

于 2013-01-20T17:09:42.387 回答
1

Arrays in PHP are zero indexed, so yes the first number in the call should be zero. You're also only picking from the beginning of the array.

Use this in stead:

for ($i = 0; $i < 5; ++$i)
{
    $id .= $chars[rand(0, 61];
}
于 2013-01-20T17:10:46.660 回答
1

Your $chars holds a string with length > 26 but your random number is between 1 and 26 (inclusive). The string index starts with 0 that is char a. For now only chars bcd...xyz1 are used. You could check the string-length dynamically and get a valid random number.

function random_id() { 
    $chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $chars_cnt = strlen($chars)-1; 
    $id = ''; 
    for ($i = 0; $i < 5; ++$i) 
    {   
        $id .= $chars[rand(0, $chars_cnt)]; 
    } 
    return $id; 
} 

echo random_id(); 
于 2013-01-20T17:13:43.823 回答