[英]prevent Random PHP generator from including zeros
I have a php script that creates a random 10 digit order number: 我有一个php脚本,可创建一个随机的10位数订单号:
// Assign order number length
$digits = 10;
// Create random order number to be stored with this order
$order_number = rand(pow(10, $digits-1), pow(10, $digits)-1);
How do I prevent this from ever including the digit zero 0
in the random 10 digit number? 如何防止此错误在随机的10位数字中包含数字0
0
? Thanks in advance! 提前致谢!
You can do fancy base conversions, but in the end, the most straightforward way is to just get a string: 您可以进行基本的转换,但最后,最直接的方法是只获取一个字符串:
function random_string($count, $available) {
$result = '';
$max = strlen($available) - 1;
for($i = 0; $i < $count; $i++) {
$result .= $available[rand(0, $max)];
}
return $result;
}
…
$order_number = random_string($digits, '123456789');
You can treat it as a number of base 9 您可以将其视为以9为底的数字
base_convert(rand(0, pow(9, $digits) - 1), 10, 9)
This will give you numbers with digits from 0 to 8. 这将为您提供从0到8的数字。
Now just add 1 to every digit to make it 1 to 9 现在只需在每个数字上加1使其变为1到9
(pow(10, $digits) - 1) / 9
will give you a number filled with ones. 会给您一个充满数字的号码。 Now just add it to your previous number and there you go:
现在,只需将其添加到您之前的号码即可,然后转到:
$digits = 10;
$order_number = (pow(10, $digits) - 1) / 9 + base_convert(rand(0, pow(9, $digits) - 1), 10, 9);
Try this :D 试试这个:D
function getRandom($from, $to){
$num = rand($from, $to);
$have_zero = true;
$strNum = strval($num);
while ($have_zero){
$have_zero = false;
for ($i = 0; $i < sizeof($strNum); $i++){
if ($strNum[$i] == '0'){
$have_zero = true;
$num = rand($from, $to);
$strNum = strval($num);
break;
}
}
}
return $num;
}
getRandom(1111111111, 9999999999);
You could use a simple function like this: 您可以使用一个简单的函数,如下所示:
function getRandom($length) {
$numbers = '';
for($i = 0; $i < $length; $i++) {
$numbers .= rand(1, 9);
}
return $numbers;
}
echo getRandom(10);
I would make a function. 我会做一个功能。
<?php
function myRandomNumberWithoutZeros($digits)
{
$result = str_replace("0", "",rand(pow(10,$digits-1), pow(10, $digits)-1)."");
$resultLength = strlen($result);
if($resultLength < $digits)
{
return intval($result.myRandomNumberWithoutZeros($digits-$resultLength));
}
return intval($result);
}
echo myRandomNumberWithoutZeros(10);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.