php生产随机数
要求
生产三种随机数
1、全数字
2、全字母,大小写
3、数字和大小写字母
代码
1 <?php 2 class RandString{ 3 //这个属性表示我们随机数的长度,也就是个数 4 private $length; 5 //要哪些类型type为1的时候就是数字类型的,为2的时候字母类型,为3的时候就是数字加上字母的随机数 6 private $type; 7 8 public function __construct($length,$type){ 9 $this->length=$length; 10 $this->type=$type; 11 } 12 13 public function randNum(){ 14 switch ($this->type){ 15 case 1: 16 return join(array_rand(range(0, 9),$this->length)); 17 break; 18 case 2: 19 return join(array_rand(array_flip(array_merge(range('a', 'z'),range('A', 'Z'))),$this->length)); 20 break; 21 case 3: 22 return join(array_rand(array_flip(array_merge(range(0, 9),range('a', 'z'),range('A', 'Z'))),$this->length)); 23 break; 24 } 25 } 26 27 } 28 29 $strNum = new RandString(4,1); 30 echo $strNum->randNum(); 31 echo '<hr/>'; 32 $strNum = new RandString(4,2); 33 echo $strNum->randNum(); 34 echo '<hr/>'; 35 $strNum = new RandString(4,3); 36 echo $strNum->randNum(); 37 echo '<hr/>'; 38 echo '<hr/>'; 39 echo '<hr/>'; 40 echo print_r(range('a', 'z')); 41 echo '<hr/>'; 42 echo print_r(array_flip(range('a', 'z'))); 43 echo '<hr/>'; 44 echo print_r(array_merge(range(0, 9),range('a', 'z'),range('A', 'Z'))); 45 echo '<hr/>'; 46 echo print_r(array_flip(array_merge(range(0, 9),range('a', 'z'),range('A', 'Z')))); 47 echo '<hr/>';
要点
这里就是几个函数的应用
1、join
join — Alias of implode()
implode — Join array elements with a string
2、array_rand
array_rand — Pick one or more random entries out of an array
3、array_flip
array_flip — Exchanges all keys with their associated values in an array
4、array_merge
array_merge — Merge one or more arrays
5、range
range — Create an array containing a range of elements