假设图案为123456。
在php中是否可以得到长度为六位数的数字,并且数字不应该重复超过一次。
456136 -- all digit are unique right
56136 -- wrong digit 4 is missing
456436 -- wrong digit 4 repeats
如果需要1-6个数字
str_shuffle('123456');
如果你需要1-9位数字
substr(str_shuffle('123456789'),0,6);
手册您可以使用 str_split()
:
$pattern = '123456';
$digits = str_split($pattern);
然后,您可以在该数组上使用 shuffle()
,因此它的元素是随机顺序的:
shuffle($digits);
最后,您可以 implode()
将随机数组还原为字符串:
$result = implode('', $digits);
转储该变量的内容:
var_dump($result);
你会得到这样的结果:
string(6) "645132"
string(6) "462513"
string(6) "542316"
总是六位数字,总是你指定的数字;
这应该给你0次重复:
$random = array();
while(count($random) != 6)
{
$random[] = rand(0, 9);
$random = array_unique($random);
}
$random = implode('', $random);
你可以试试:
$nums = array();
while(count($nums)<=6){
$rand = rand(0,9);
if(!in_array($rand, $nums)){
$nums[] = $rand;
}
}
echo implode('',$nums);
演示:运行1:http://codepad.org/31AKqeYz
运行2: http://codepad.org/ckuUQCP3