网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 php生成随机数的三种方法
内容
    如何用php生成1-10之间的不重复随机数?
    例1,使用shuffle函数生成随机数。
    1<?php
    2$arr=range(1,10);
    3shuffle($arr);
    4foreach($arr as $values)
    5{
    6 echo $values." ";
    7}
    8?>
    例2,使用array_unique函数生成随机数。
    1<?php
    2$arr=array();
    3while(count($arr)<10)
    4{
    5 $arr[]=rand(1,10);
    6 $arr=array_unique($arr);
    7}
    8echo implode(" ",$arr);
    9?>
    例3,使用array_flip函数生成随机数,可以去掉重复值。
    01<?php
    02$arr=array();
    03$count1=0;
    04$count = 0;
    05$return = array();
    06while ($count < 10)
    07 {
    08 $return[] = mt_rand(1, 10);
    09 $return = array_flip(array_flip($return));
    10 $count = count($return);
    11 } //www.jbxue.com
    12foreach($return as $value)
    13 {
    14 echo $value." ";
    15 }
    16echo "<br/>";
    17$arr=array_values($return);// 获得数组的值
    18foreach($arr as $key)
    19echo $key." ";
    20?>
    php随机数生成函数示例
    01<?php
    02function randpw($len=8,$format='ALL'){
    03$is_abc = $is_numer = 0;
    04$password = $tmp ='';
    05switch($format){
    06case 'ALL':
    07$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    08break;
    09case 'CHAR':
    10$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    11break;
    12case 'NUMBER':
    13$chars='0123456789';
    14break;
    15default :
    16$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    17break;
    18} // www.jbxue.com
    19mt_srand((double)microtime()*1000000*getmypid());
    20while(strlen($password)<$len){
    21$tmp =substr($chars,(mt_rand()%strlen($chars)),1);
    22if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){
    23$is_numer = 1;
    24}
    25if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){
    26$is_abc = 1;
    27}
    28$password.= $tmp;
    29}
    30if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){
    31$password = randpw($len,$format);
    32}
    33return $password;
    34}
    35for($i = 0 ; $i < 10; $i++){
    36echo randpw(8,'NUMBER');
    37echo "<br>";
    38}
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/13 8:53:51