php生成不等于某数的随机数

2024-11-22 20:41:12
推荐回答(2个)
回答(1):

例1,使用shuffle函数生成随机数。
1
2 $arr=range(1,10);

3 shuffle($arr);

4 foreach($arr as $values)

5 {

6 echo $values." ";

7 }

8 ?>

例2,使用array_unique函数生成随机数。

1
2 $arr=array();

3 while(count($arr)<10)

4 {

5 $arr[]=rand(1,10);

6 $arr=array_unique($arr);

7 }

8 echo implode(" ",$arr);

9 ?>

例3,使用array_flip函数生成随机数,可以去掉重复值。

01
02 $arr=array();

03 $count1=0;

04 $count = 0;

05 $return = array();

06 while ($count < 10)

07 {

08 $return[] = mt_rand(1, 10);

09 $return = array_flip(array_flip($return));

10 $count = count($return);

11 } //www.jbxue.com

12 foreach($return as $value)

13 {

14 echo $value." ";

15 }

16 echo "
";

17 $arr=array_values($return);// 获得数组的值

18 foreach($arr as $key)

19 echo $key." ";

20 ?>

php随机数生成函数示例

01
02 function randpw($len=8,$format='ALL'){

03 $is_abc = $is_numer = 0;

04 $password = $tmp ='';

05 switch($format){

06 case 'ALL':

07 $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

08 break;

09 case 'CHAR':

10 $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

11 break;

12 case 'NUMBER':

13 $chars='0123456789';

14 break;

15 default :

16 $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

17 break;

18 } // www.jbxue.com

19 mt_srand((double)microtime()*1000000*getmypid());

20 while(strlen($password)<$len){

21 $tmp =substr($chars,(mt_rand()%strlen($chars)),1);

22 if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){

23 $is_numer = 1;

24 }

25 if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){

26 $is_abc = 1;

27 }

28 $password.= $tmp;

29 }

30 if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){

31 $password = randpw($len,$format);

32 }

33 return $password;

34 }

35 for($i = 0 ; $i < 10; $i++){

36 echo randpw(8,'NUMBER');

37 echo "
";

38 }

回答(2):

function my_rand($min,$max){
static $target=null;
$rand = rand($min,$max);
if($target==$rand){
if($rand+1>=$max){
$target = $rand-1;

}else{
$target = $rand+1;

}

}else{
$target =$rand;

}
return $target;

}