生成具有预定义长度PHP的随机数 [英] Generate a random number with pre-defined length PHP

查看:85
本文介绍了生成具有预定义长度PHP的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用mt_rand()创建一个函数以生成一个真正的随机数,因为rand()不够.

I'm trying to create a function using mt_rand() in order to generate a truly random number, since rand() just isn't suffice.

问题是我需要预定义数字的长度,比如说我需要一个10位数的随机数.

The problem is I need to pre-define the length of the number, say I need a 10 digit random number.

无论如何,我一直在搞乱,这就是我想出的:

Anyway, I've been messing around and this is what I've come up with:

    function randomNumber($length) {
        $min = str_repeat(0, $length-1) . 1;
        $max = str_repeat(9, $length);
        return mt_rand($min, $max);   
    }

在理论上应该起作用(据我所知),但事实并非如此.该长度是完全随机的,并且还会抛出负值.

In theory that should work (as far as I can tell), but it doesn't. The length is completely random and it also throws out negative values.

有什么想法吗?

推荐答案

除非您拥有这些量子静态事物之一,否则您将无法获得真正的随机数.但是,在基于Unix的操作系统上,如果确实需要/dev/urandom,则它可以实现更多随机性".

Unless you have one of those quantum-static thingies, you can't get a truly random number. On Unix-based OSes, however, /dev/urandom works for "more randomness", if you really need that.

无论如何,如果您想要一个n位数字,那正是您应该得到的:n个单独的数字.

Anyway, if you want an n-digit number, that's exactly what you should get: n individual digits.

function randomNumber($length) {
    $result = '';

    for($i = 0; $i < $length; $i++) {
        $result .= mt_rand(0, 9);
    }

    return $result;
}

您的现有代码无法正常工作的原因是,由于0000...01仍然是1mt_rand,并且mt_rand的范围不是无限的.负数是整数溢出.

The reason your existing code isn't working is because 0000...01 is still 1 to mt_rand, and also that mt_rand's range isn't infinite. The negative numbers are integer overflows.

这篇关于生成具有预定义长度PHP的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆