PHP randomly removes several different numbers from an array

PHP中文网
Release: 2023-02-28 19:58:01
Original
1540 people have browsed it

PHP randomly extracts several different numbers from an array

The first algorithm is other people’s ideas on CSDN

$num = 0; 
 $array = array(1, 2, 3, 4, 5, 6, 7, 8, 9); 
 $arr = array(); 
 $g = 5; 
 $tag = true; 
 while ($tag) { 
   $count = count($array); 
   $t = rand(0, 1); 
   if ($t == 1) { 
     $arr[] = $array[$num]; 
     unset($array[$num]); 
   } 
   $num ++; 
   if (count($arr) == $g) { 
     $tag = false; 
   } 
   if ($num == $count) { 
     $num = 0;  //循环 
   } 
 } 
var_dump($arr);
Copy after login

The second algorithm is my own idea.

You can replace the data with the last unobtained data after each fetching, and then randomly obtain values ​​from the unobtained data

function swap(&$a, &$b) 
{ 
  $temp = $b; 
  $b = $a; 
  $a = $temp; 
} 
   
   
$result = array(); 
$src = array(); 
for($i = 0 ; $i < 40 ; $i++) 
{ 
  $src[] = $i + 1; 
} 
$arr_len = count($src); 
$count = 20; 
$index = 0; 
while($index < $count) 
{ 
  $random = rand(0, $arr_len - $index - 1); 
  $result[] = $src[$random]; 
  swap($src[$random] , $src[$arr_len - $index - 1]); 
  $index += 1; 
} 
   
   
print_r(json_encode($result)); 
print_r(json_encode($src));
Copy after login

The above is how PHP randomly takes out several different values ​​from an array For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!