PHP随机X位数 [英] php random x digit number

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

问题描述

我需要创建一个x位数的随机数.

I need to create a random number with x amount of digits.

因此,假设x为5,我需要一个数字,例如. 35562 如果x为3,则它将抛出类似的结果; 463

So lets say x is 5, I need a number to be eg. 35562 If x is 3, then it would throw back something like; 463

有人可以告诉我这是怎么做的吗?

Could someone show me how this is done?

推荐答案

您可以使用 rand() pow() 一起实现: /p>

You can use rand() together with pow() to make this happen:

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);

这将输出100到999之间的数字.这是因为10 ^ 2 = 100和10 ^ 3 = 1000,然后您需要将其减去一个,以使其处于所需的范围内.

This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.

如果005也是有效的示例,则可以使用以下代码在其前添加零:

If 005 also is a valid example you'd use the following code to pad it with leading zeros:

$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

这篇关于PHP随机X位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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