PHP에서 난수를 생성하는 방법 요약

php中世界最好的语言
풀어 주다: 2023-03-20 19:10:02
원래의
1967명이 탐색했습니다.

난수는 매우 일반적으로 사용되는 방법입니다. 이 글에서는 PHP에서 난수를 생성하는 방법을 4가지 방법으로 나누어서 각 방법의 비교를 참고하실 수 있습니다.

첫 번째 방법은 mt_rand()를 사용합니다.

function GetRandStr($length){ 
$str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
$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;
로그인 후 복사

두 번째 방법(가장 빠름)

function make_password( $length = 8 ) 
{ 
 // 密码字符集,可任意添加你需要的字符 
 $chars = array(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, 
 &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;,&#39;m&#39;, &#39;n&#39;, &#39;o&#39;, &#39;p&#39;, &#39;q&#39;, &#39;r&#39;, &#39;s&#39;, 
 &#39;t&#39;, &#39;u&#39;, &#39;v&#39;, &#39;w&#39;, &#39;x&#39;, &#39;y&#39;,&#39;z&#39;, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, 
 &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39;, &#39;I&#39;, &#39;J&#39;, &#39;K&#39;, &#39;L&#39;,&#39;M&#39;, &#39;N&#39;, &#39;O&#39;, 
 &#39;P&#39;, &#39;Q&#39;, &#39;R&#39;, &#39;S&#39;, &#39;T&#39;, &#39;U&#39;, &#39;V&#39;, &#39;W&#39;, &#39;X&#39;, &#39;Y&#39;,&#39;Z&#39;, 
 &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;!&#39;, 
 &#39;@&#39;,&#39;#&#39;, &#39;$&#39;, &#39;%&#39;, &#39;^&#39;, &#39;&&#39;, &#39;*&#39;, &#39;(&#39;, &#39;)&#39;, &#39;-&#39;, &#39;_&#39;, 
 &#39;[&#39;, &#39;]&#39;, &#39;{&#39;, &#39;}&#39;, &#39;<&#39;, &#39;>&#39;, &#39;~&#39;, &#39;`&#39;, &#39;+&#39;, &#39;=&#39;, &#39;,&#39;, 
 &#39;.&#39;, &#39;;&#39;, &#39;:&#39;, &#39;/&#39;, &#39;?&#39;, &#39;|&#39;); 
 // 在 $chars 中随机取 $length 个数组元素键名 
 $keys = array_rand($chars, $length); 
 $password = &#39;&#39;; 
 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; 
}
로그인 후 복사

네 번째 방법은 문자열을 뒤섞습니다.

function getrandstr(){ 
$str=&#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890&#39;; 
$randStr = str_shuffle($str);//打乱字符串 
$rands= substr($randStr,0,6);//substr(string,start,length);返回字符串的一部分 
return $rands; 
}
로그인 후 복사

/ /인증 코드 생성 시작(함수로 직접 생성, 더 편리하고 빠릅니다)

$code = rand(10000, 99999);
로그인 후 복사

php mt_rand는 0~1개의 임의 소수 생성 효과를 비교합니다.

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++){ 
 echo lcg_value().PHP_EOL; 
} 
?>
로그인 후 복사

출력:

0.11516515851995
0.064684551575297
0.68275174031189
0.55730746529099
0.702150088 78091

0~1개의 난수 생성 방법 비교

1. 실행 시간 비교

100,000번 실행 기준 on mt_rand() 및 mt_getrandmax() 알고리즘의 실행 시간

<?php
/**
 * 生成0~1随机小数
 * @param Int $min
 * @param Int $max
 * @return Float
 */
function randFloat($min=0, $max=1){
 return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}

// 获取microtime
function get_microtime(){
 list($usec, $sec) = explode(&#39; &#39;, microtime());
 return (float)$usec + (float)$sec;
}

// 记录开始时间
$starttime = get_microtime();

// 执行10万次获取随机小数
for($i=0; $i<100000; $i++){
 randFloat();
}

// 记录结束时间
$endtime = get_microtime();

// 输出运行时间
printf("run time %f ms\r\n", ($endtime-$starttime)*1000);
?>
로그인 후 복사

출력: 실행 시간 266.893148 ms

lcg_value() 100,000회 실행 시간

<?php
// 获取microtime
function get_microtime(){
 list($usec, $sec) = explode(&#39; &#39;, microtime());
 return (float)$usec + (float)$sec;
}
// 记录开始时间
$starttime = get_microtime();
// 执行10万次获取随机小数
for($i=0; $i<100000; $i++){
 lcg_value();
}
// 记录结束时间
$endtime = get_microtime();
// 输出运行时间
printf("run time %f ms\r\n", ($endtime-$starttime)*1000);
?>
로그인 후 복사

출력: 실행 시간 86.178064 ms

실행 시간 비교 , lcg_value()는 직접적으로 네이티브 PHP 메소드이고 mt_rand()와 mt_getrandmax()는 두 메소드를 호출하고 계산을 수행해야 하기 때문에 lcg_value()의 실행 시간은 약 3배 더 빠릅니다.

2. 무작위 효과 비교

mt_rand() 및 mt_getrandmax() 알고리즘을 기반으로 한 무작위 효과

<?php
/**
 * 生成0~1随机小数
 * @param Int $min
 * @param Int $max
 * @return Float
 */
function randFloat($min=0, $max=1){
 return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}
header(&#39;content-type: image/png&#39;);
$im = imagecreatetruecolor(512, 512);
$color1 = imagecolorallocate($im, 255, 255, 255);
$color2 = imagecolorallocate($im, 0, 0, 0);
for($y=0; $y<512; $y++){
 for($x=0; $x<512; $x++){
  $rand = randFloat();
  if(round($rand,2)>=0.5){
   imagesetpixel($im, $x, $y, $color1);
  }else{
   imagesetpixel($im, $x, $y, $color2);
  }
 }
}
imagepng($im);
imagedestroy($im);
?>
로그인 후 복사

LCg_value() 무작위 효과

<?php
header(&#39;content-type: image/png&#39;);
$im = imagecreatetruecolor(512, 512);
$color1 = imagecolorallocate($im, 255, 255, 255);
$color2 = imagecolorallocate($im, 0, 0, 0);
for($y=0; $y<512; $y++){
 for($x=0; $x<512; $x++){
  $rand = lcg_value();
  if(round($rand,2)>=0.5){
   imagesetpixel($im, $x, $y, $color1);
  }else{
   imagesetpixel($im, $x, $y, $color2);
  }
 }
}
imagepng($im);
imagedestroy($im);
?>
로그인 후 복사

관련 권장 사항:

JS 난수 코드 공유 구현

JavaScript 난수 생성기 구현 방법

MySQL을 구현하여 난수 생성 및 문자열 연결 방법


위 내용은 PHP에서 난수를 생성하는 방법 요약의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!