dongqi6486 2016-01-06 09:21
浏览 29
已采纳

在PHP中生成非常Uniquer的数字 - CodeIgniter

I am developing a very big application where i want to create very very unique random numbers which will never ever match the previous records.Here is my code

function random_number($maxlength = 17) {
    $chary = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
    $return_str = "";
    for ( $x=0; $x<=$maxlength; $x++ ) {
        $return_str .= $chary[rand(0, count($chary))];
    }
    return $return_str;
}

Now it works fine but some time it give me error

Notice: Undefined offset: 62 in test.php on line 8

Where line 8 is

$return_str .= $chary[rand(0, count($chary))];

Can anyone fix this for me?

Secondly is there any function in CI for random numbers?

  • 写回答

3条回答 默认 最新

  • douchen2595 2016-01-06 09:25
    关注

    From the manual,

    int rand ( int $min , int $max )

    If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

    So you have to change the range parameter in rand() function, from rand(0, count($chary)) to rand(0, count($chary)-1)

    function random_number($maxlength = 17) {
        $chary = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
        $return_str = "";
        for ( $x=0; $x<=$maxlength; $x++ ) {
            $return_str .= $chary[rand(0, count($chary)-1)];
        }
        return $return_str;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置