Home  >  Article  >  Backend Development  >  PHP non-repeating random number generation method_PHP tutorial

PHP non-repeating random number generation method_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:33848browse

The principle is very simple. First write a function to generate one of the 36 characters 0-z. Each call to the getOptions() method generates a character, which is stored as follows: array[0] = 0, array[1] = 1, …, array[35] = z.

Array ( 
	[0] => 0 
	[1] => 1 
	[2] => 2 
	[3] => 3 
	[4] => 4 
	[5] => 5 
	[6] => 6 
	[7] => 7 
	[8] => 8 
	[9] => 9 
	[10] => a 
	[11] => b 
	[12] => c 
	[13] => d 
	[14] => e 
	[15] => f 
	[16] => g 
	[17] => h 
	[18] => i 
	[19] => j 
	[20] => k 
	[21] => l 
	[22] => m 
	[23] => n 
	[24] => o 
	[25] => p 
	[26] => q 
	[27] => r 
	[28] => s 
	[29] => t 
	[30] => u 
	[31] => v 
	[32] => w 
	[33] => x 
	[34] => y 
	[35] => z 
)

Then randomly generate a number between 0-35 as the index, which is actually to randomly pick out a number from the above array as the first character in the variable $result. This random index will then be assigned as the last one in the array, and it will not participate in the next round of random selection.

<?php
// 生成0123456789abcdefghijklmnopqrstuvwxyz中的一个字符
function getOptions()
{
 	$options = array();
 	$result = array();
 	for($i=48; $i<=57; $i++)
 	{
     	array_push($options,chr($i));  
 	}
 	for($i=65; $i<=90; $i++)
  	{
      	$j = 32;
      	$small = $i + $j;
      	array_push($options,chr($small));
	}
 	return $options;
}
/*
$e = getOptions();
for($j=0; $j<150; $j++)
{
	echo $e[$j];
}
*/
$len = 10;
// 随机生成数组索引,从而实现随机数
for($j=0; $j<100; $j++)
{
 	$result = "";
 	$options = getOptions();
 	$lastIndex = 35;
 	while (strlen($result)<$len)
 	{
  		// 从0到35中随机取一个作为索引
		$index = rand(0,$lastIndex);
		// 将随机数赋给变量 $chr
  		$chr = $options[$index];
		// 随机数作为 $result 的一部分
  		$result .= $chr;
  		$lastIndex = $lastIndex-1;
		// 最后一个索引将不会参与下一次随机抽奖
  		$options[$index] = $options[$lastIndex];
 	}
 	echo $result."n";
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752456.htmlTechArticleThe principle is very simple. First write a function to generate one of the 36 characters 0-z. Each call to the getOptions() method generates a character, and they are stored as follows: array[0] = 0, array[1] = 1...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn