PHP生成隨機數

2021-08-21 07:51:36 字數 3452 閱讀 5192

function

getrandstr

($length)

return $randstr;

}$number=getrandstr(

6);echo $number;

function

make_password

( $length = 8 )

', '<',

'>',

'~',

'`',

'+',

'=',

',',

'.',

';',

':',

'/',

'?',

'|');

// 在 $chars 中隨機取 $length 個陣列元素鍵名

$keys = array_rand($chars, $length);

$password =

'';for($i =

0; $i < $length; $i++)

return $password;

}

function

get_password

( $length = 8 )

function

getrandstr

()

$code = rand(10000, 99999);

lcg_value說明

float lcg_value ( void )

lcg_value() 返回範圍為 (0, 1) 的乙個偽隨機數。本函式組合了週期為 2^31 - 85 和 2^31 - 249 的兩個同餘發生器。本函式的週期等於這兩個素數的乘積。

返回:範圍為 (0, 1) 的偽隨機數。

<?php

for($i=

0; $i<

5; $i++)

?>

輸出:0.11516515851995

0.064684551575297

0.68275174031189

0.55730746529099

0.70215008878091

兩種生成0~1隨機小數方法進行比較

執行10萬次基於mt_rand()與mt_getrandmax()演算法的執行時間

<?php

/*** 生成0~1隨機小數

* @param int $min

* @param int $max

* @return float

*/function

randfloat

($min=0, $max=1)

// 獲取microtime

function

get_microtime

()

// 記錄開始時間

$starttime = get_microtime();

// 執行10萬次獲取隨機小數

for($i=

0; $i<

100000; $i++)

// 記錄結束時間

$endtime = get_microtime();

// 輸出執行時間

printf(

"run time %f ms\r\n", ($endtime-$starttime)*

1000);

?>

輸出:run time 266.893148 ms 

執行10萬次lcg_value()的執行時間

<?php

// 獲取microtime

function

get_microtime

()

// 記錄開始時間

$starttime = get_microtime();

// 執行10萬次獲取隨機小數

for($i=

0; $i<

100000; $i++)

// 記錄結束時間

$endtime = get_microtime();

// 輸出執行時間

printf(

"run time %f ms\r\n", ($endtime-$starttime)*

1000);

?>

輸出:run time 86.178064 ms

執行時間上比較,因為lcg_value()直接是php原生方法,而mt_rand()與mt_getrandmax()需要呼叫兩個方法,並需要進行計算,因此lcg_value()的執行時間大約快3倍。

基於mt_rand()與mt_getrandmax()演算法的隨機效果

<?php

/*** 生成0~1隨機小數

* @param int $min

* @param int $max

* @return float

*/function

randfloat

($min=0, $max=1)

header(

'content-type: image/png');

$im = imagecreatetruecolor(

512,

512);

$color1 = imagecolorallocate($im,

255,

255,

255);

$color2 = imagecolorallocate($im,

0, 0,

0);for($y=

0; $y<

512; $y++)

else}}

imagepng($im);

imagedestroy($im);

?>

lcg_value()的隨機效果

<?php

header(

'content-type: image/png');

$im = imagecreatetruecolor(

512,

512);

$color1 = imagecolorallocate($im,

255,

255,

255);

$color2 = imagecolorallocate($im,

0, 0,

0);for($y=

0; $y<

512; $y++)

else}}

imagepng($im);

imagedestroy($im);

?>

php生成隨機數

生成1 10之間的隨機數,不重複。方法一 用shuffle函式。arr range 1,10 shuffle arr foreach arras values 方法二 用array unique函式.arr array while count arr 10 echoimplode arr 方法三 用...

PHP生成隨機數 rand

php 4,php 5 rand 產生乙個隨機整數 intrand void intrand int min,int max 如果沒有提供可選引數min和max,rand 返回 0 到 getrandmax 之間的偽隨機整數。例如想要 5 到 15 包括 5 和 15 之間的隨機數,用 rand 5...

PHP函式生成隨機數

通常情況下,當我們要生成乙個隨機字串時,總是先建立乙個字元池,然後用乙個迴圈和mt rand 或rand 生成php隨機數,從字元池中隨機選取字元,最後拼湊出需要的長度,如下 function randomkeys length fckpd 0pound 字元池 key for i 0 i leng...