Home > Backend Development > PHP Problem > How to generate non-repeating random numbers in php

How to generate non-repeating random numbers in php

王林
Release: 2023-03-07 09:44:01
Original
3254 people have browsed it

How to generate non-repeating random numbers in php: first use the range function to create an array containing elements in a specified range; then use the shuffle function to rearrange the elements in the array in random order; finally take out a section of the array element.

How to generate non-repeating random numbers in php

Implementation principle:

Shuffle the order of the array and then take a certain segment of the array.

(Related video recommendations: java course)

The method is as follows:

Method one:

The range() function creates an array containing a specified range of elements.

shuffle() function rearranges the elements in the array in random order.

<?php 
//range 是将1到100 列成一个数组 
$numbers = range (1,100); 
//shuffle 将数组顺序随即打乱 
shuffle ($numbers); 
//array_slice 取该数组中的某一段 
$result = array_slice($numbers,0,3); 
print_r($result); 
?>
Copy after login

Method 2:

<?php 
$numbers = range (1,20); 
srand ((float)microtime()*1000000); 
shuffle ($numbers); 
while (list (, $number) = each ($numbers)) { 
echo "$number "; 
} 
?>
Copy after login

Method 3:

Use PHP to randomly generate 5 non-repeating values ​​between 1-20

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

Or if you don’t shuffle

<?php 
$tmp=array(); 
while(count($tmp)<5){ 
$tmp[]=mt_rand(1,20); 
$tmp=array_unique($tmp); 
} 
print join(&#39;,&#39;,$tmp); 
?>
Copy after login

Related recommendations: php training

The above is the detailed content of How to generate non-repeating random numbers in php. For more information, please follow other related articles on the PHP Chinese website!

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