Two ways PHP generates random Numbers instance code outputs random IP

  • 2020-03-31 21:38:34
  • OfStack

Share the three methods of generating random Numbers in PHP, generate random Numbers between 1 and 10 that do not repeat, and generate random Numbers in PHP that do not repeat, for your reference.

How do I generate non-repeating random Numbers between 1-10 in PHP?

In example 1, random Numbers are generated using the shuffle function.


<?php
$arr=range(1,10);
shuffle($arr);
foreach($arr as $values)
{
  echo $values." ";
}
?>

In example 2, a random number is generated using the array_unique function.


<?php
$arr=array();
while(count($arr)<10)
{
  $arr[]=rand(1,10);
  $arr=array_unique($arr);
}
echo implode(" ",$arr);
?>

In example 3, the array_flip function is used to generate random Numbers, which can remove duplicate values.


<?php
$arr=array();
$count1=0;
$count = 0;
$return = array();
while ($count < 10) 
 {
  $return[] = mt_rand(1, 10);
  $return = array_flip(array_flip($return));
  $count = count($return);
 } //www.jb51.net
foreach($return as $value)
 {
  echo $value." ";
 }
echo "<br/>";
$arr=array_values($return);//Gets the value of the array
foreach($arr as $key)
echo $key." ";
?>

I am an asp programmer, this is the first time to write PHP program, a little experience to share


<?php 
$ip2id= round(rand(600000, 2550000) / 10000); //The first way is to generate directly
$ip3id= round(rand(600000, 2550000) / 10000); 
$ip4id= round(rand(600000, 2550000) / 10000); 
//Here is the second method, which randomly selects the following data
$arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","60","66","218","218","62","63","64","66","66","122","211"); 
$randarr= mt_rand(0,count($arr_1)-1); 
$ip1id = $arr_1[$randarr]; 
echo $ip1id; 
echo "."; 
echo $ip2id; 
echo "."; 
echo $ip3id; 
echo "."; 
echo $ip4id; 
?>

The output result of example is 218.28.131.182
The characteristics of this program is that the first field of the generated IP in the specified range, a few Settings are domestic common number segment, that is, the IP address generated is mostly domestic
Core code:


<?php 
$arr_1 = array("http://66.249.89.99","http://66.249.89.104","http://74.125.71.105"); 
$randarr= mt_rand(0,count($arr_1)-1); 
$gip= $arr_1[$randarr]; 
echo $gip."$randarr"; 
?>

Related articles: