php生成隨機的6位數字
㈠ php生成隨機數的幾種方法
PHP生成隨機數的幾種方法
第一種方法使用mt_rand()函數生成隨機數,示例代碼如下:
function GetRandStr($length){
$str='';
$len=strlen($str)-1;
$randstr='';
for($i=0;$i<$length;$i++){
$num=mt_rand(0,$len);
$randstr .= $str[$num];
}
return $randstr;
$number=GetRandStr(6);
echo $number;
第二種方法使用array_rand()和md5函數生成隨機字元串,代碼如下:
function make_password( $length = 8 ) { // 密碼字元集,可任意添加你需要的字元 $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',', '.', ';', ':', '/', '?', '|'); // 在 $chars 中隨機取 $length 個數組元素鍵名 $keys = array_rand($chars, $length); $password = ''; for($i = 0; $i < $length; $i++) { // 將 $length 個數組元素連接成字元串 $password .= $chars[$keys[$i]]; } return $password; }
第三種方法取當前時間戳,代碼示例為:
function get_password( $length = 8 ) { $str = substr(md5(time()), 0, $length);//md5加密,time()當前時間戳 return $str; }
第四種方法使用str_shuffle()函數打亂字元串,生成隨機字元串,代碼如下:
function getrandstr(){ $str=''; $randStr = str_shuffle($str);//打亂字元串 $rands= substr($randStr,0,6);//substr(string,start,length);返回字元串的一部分 return $rands; }
第五種方法生成四位隨機驗證碼,代碼如下:
$code = rand(10000, 99999);
比較mt_rand()生成0~1隨機小數的效果與lcg_value()方法:
兩種方法進行執行時間比較,lcg_value()執行時間大約快3倍。
兩種方法進行隨機效果比較,生成的圖像效果對比。
㈡ Php中生成6位隨機數並顯示
Php中生成6位隨機數並顯示實現如下:
1、使用shuffle函數生成隨機數。
<?php
$arr=range(100000,999999);
shuffle($arr);
foreach($arras$values)
{
echo$values." ";//顯示隨機數
}
?>2、使用array_unique函數生成隨機數。
<?php
$arr=array();
while(count($arr)<10)
{
$arr[]=rand(1,10);
$arr=array_unique($arr);
}echoimplode(" ",$arr);
?>
(2)php生成隨機的6位數字擴展閱讀:
PHP生成隨機數的兩種方法:
1、rand()函數:
//無參數:rand()函數用戶獲取隨機數。
echo rand() . " ";//得到一個不定位數的隨機數
//帶參數:rand($min,$max),$min表示從XX開始取值,$max表示最大隻能為XX。
echo rand(5, 15);//在5~15之間取一個數
注意:mt_rand() 用法跟rand()類似,但是mt_rand()的執行效率更高。
2、使用array_flip函數生成隨機數,可以去掉重復值。
㈢ php程序如何產生隨機數
$i = rand(10,100000);隨機產生10到100000之間的一個數字
<?php
echo "<table><tr>";
for($i=0;$i<20;$i++)
{
echo "<td>",rand(10,100000),"</td>";
if($i==9)
{
echo "</tr><tr>";
}
}
echo "</tr></table>";
?>