dongshou1991 2013-03-04 09:24
浏览 55
已采纳

在PHP中创建长度为5的唯一ID

I know the uniqid() method to create lots of unique ids with a length of 7 or more, but what I want to create is a length of 5 unique id with no collision.

Is it possible to create 220.000 unique id's with a length of 5 and check if there is any collision?

  • 写回答

3条回答 默认 最新

  • dongniaoli1822 2013-03-04 09:41
    关注

    You can try

    for($i = 0; $i < 10 ; $i++)
    {
        echo randString(5),PHP_EOL ;
    }
    

    Output

    7fh96
    G93fd
    97Q7E
    90Wku
    7Vby9
    4678f
    S11oe
    67688
    19D36
    KC1bQ
    

    Simple Collision Test

    $hash = array();
    $collision = 0;
    while ( count($hash) < 220000 ) {
        $r = randString(5);
        if (isset($hash[$r])) {
            $collision ++;
            continue;
        }
        $hash[$r] = 1;
    }
    
    print(($collision / 220000)  * 100 . "% - ($collision)");
    

    Tested 100,000 times and always collision is always less that 0.02 which makes the function efficient for a 5 character set

    0.011818181818182% - (26)
    

    Function Used

    function randString($length) {
        $char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $char = str_shuffle($char);
        for($i = 0, $rand = '', $l = strlen($char) - 1; $i < $length; $i ++) {
            $rand .= $char{mt_rand(0, $l)};
        }
        return $rand;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加