Home > Backend Development > PHP Tutorial > PHP n non-repeating random number generation code_PHP tutorial

PHP n non-repeating random number generation code_PHP tutorial

WBOY
Release: 2016-07-21 15:45:26
Original
1099 people have browsed it

Copy code The code is as follows:

//range is to list 1 to 100 into an array
$numbers = range (1,100);
//shuffle shuffles the order of the array
shuffle ($numbers);
//array_slice takes a certain segment of the array
$no=6 ;
$result = array_slice($numbers,0,$no);
for ($i=0;$i<$no;$i++){
echo $result[$i]."
";
}
print_r($result);
?>

Copy code The code is as follows:

//range is to list 1 to 42 into an array
$numbers = range (1,42);
//shuffle will disrupt the order of the array.
shuffle ($numbers);
//array_slice takes a certain segment of the array
$result = array_slice($numbers,0,3);
print_r($result);

Method 2
Copy code The code is as follows:

$numbers = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (, $number) = each ($numbers)) {
echo "$number ";
}
?>
Method 3
Use PHP to randomly generate 5 unique values ​​between 1-20. How to do it
Copy code The code is as follows:

function NoRand($begin=0,$end=20 ,$limit=5){
$rand_array=range($begin,$end);
shuffle($rand_array);//Call the ready-made array random arrangement function
return array_slice($rand_array,0 ,$limit);//Intercept the first $limit
}
print_r(NoRand());
?>

or if not shuffle
Copy code The code is as follows:

$tmp=array();
while(count($tmp )<5){
$tmp[]=mt_rand(1,20);
$tmp=array_unique($tmp);
}
print join(',',$tmp) ;
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320353.htmlTechArticleCopy the code as follows: ?php //range is to list 1 to 100 into an array $numbers = range ( 1,100); //shuffle shuffles the order of the array shuffle ($numbers); //array_slice takes the array...
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