How to generate 100 different random numbers in php

青灯夜游
Release: 2023-03-13 07:42:01
Original
3804 people have browsed it

Method: 1. Define an empty array for placing random numbers; 2. Use "while (array length

How to generate 100 different random numbers in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php generates 100 Different random numbers

<?php
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/
function unique_rand($min, $max, $num) {
  $count = 0;
  $return = array();
  while ($count < $num) {
      $return[] = mt_rand($min, $max);
      $return = array_flip(array_flip($return));
      $count = count($return);
  }
  shuffle($return);
  return $return;
}
$arr = unique_rand(1, 1000, 100);
sort($arr);
$result = &#39;&#39;;
for($i=0; $i < count($arr);$i++)
{
  $result .= $arr[$i].&#39;,&#39;;
}
$result = substr($result, 0, -1);
echo $result;
?>
Copy after login

Output result:

5,14,36,59,61,65,70,72,95,103,105,114,124,138,142,143,153,159,170,174,175,184,186,189,207,210,214,220,254,256,257,259,268,273,280,281,290,293,295,303,309,315,316,321,327,359,364,370,416,420,429,433,434,436,438,449,464,493,505,558,563,568,570,593,599,637,639,646,656,659,670,687,695,709,713,719,722,731,733,736,749,750,784,803,807,812,835,849,859,893,899,914,937,941,948,951,960,969,991,992
Copy after login

Description:

##mt_rand() Use Mersenne Twister The algorithm returns random integers. Syntax:

mt_rand(min,max)
Copy after login
Returns a random integer between min and max.

array_flip() The function is used to reverse/exchange the key names in the array and the corresponding associated key values. Using the array_flip() function we can remove duplicate elements from the array.

Just use array_flip() to swap the key names and key values ​​to remove duplicate values; then use array_flip() to swap the key names and key values ​​back again

count() The function returns the number of elements in the array, that is, calculates the length of the array.

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to generate 100 different 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