How to generate unique random numbers in PHP

WBOY
Release: 2016-08-08 09:33:16
Original
937 people have browsed it

How to generate unique random numbers in PHP

Whether it is a web application, a WAP or a mobile application, random numbers have their place. In several small projects that I have been exposed to recently, I often need to deal with random numbers or random arrays. Therefore, I will summarize some common methods for how to generate non-repeating random numbers in PHP (ps: Methods 1, 4, and 5 are my Commonly used ones, the rest are collected from the Internet)

Method 1:

<span><?php 
$numbers = range (1,50); <span>//shuffle 将数组顺序随即打乱 </span> shuffle ($numbers); <span>//array_slice 取该数组中的某一段 </span> $num=6; 
$result = array_slice($numbers,0,$num); 
print_r($result); 
?></span>
Copy after login

Method 2:

<span><?php 
$numbers = range (1,20); <span>//播下随机数发生器种子,可有可无,测试后对结果没有影响</span> srand ((<span>float</span>)microtime()*1000000); 
shuffle ($numbers); <span>//跳过list第一个值(保存的是索引)</span> <span>while</span> (<span>list</span>(, $number) = each ($numbers)) { <span>echo</span> <span>"$number "</span>; 
} 
?></span>
Copy after login

Method 3:

<span><?php <span>function</span> NoRand($begin=0,$end=20,$limit=5){ 
$rand_array=range($begin,$end); 
shuffle($rand_array);<span>//调用现成的数组随机排列函数 </span> <span>return</span> array_slice($rand_array,0,$limit);<span>//截取前$limit个 </span> } 
print_r(NoRand()); 
?></span>
Copy after login

The above can randomly generate 5 non-repeating values ​​between 1-20

Method 4:

<span><?php 
$tmp=<span>array</span>(); <span>while</span>(count($tmp)<5){ 
$tmp[]=mt_rand(1,20); 
$tmp=array_unique($tmp); 
} 
print_r($tmp);
?></span>
Copy after login

Method 5:

<span><?php 
$tmp = range(1,30);
print_r(array_rand($tmp,10));
?></span>
Copy after login

This may be simpler than calling it (ps: if the step size is specified in the range, you must pay attention to whether the second parameter of array_rand exceeds the length of $tmp).



The above introduces how to generate non-repeating random numbers in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template