Share the following three methods for php to generate random numbers: generate random numbers that are not repeated between 1 and 10. example of generating random numbers that are not repeated by php, for more information about how to use php to generate random numbers between 1 and 10?
Example 1: Use the shuffle function to generate a random number.
<?php$arr=range(1,10);shuffle($arr);foreach($arr as $values){ echo $values." ";}?>
Example 2: Use the array_unique function to generate a random number.
<?php$arr=array();while(count($arr)<10){ $arr[]=rand(1,10); $arr=array_unique($arr);}echo implode(" ",$arr);?>
Example 3: Use the array_flip function to generate a random number and remove the duplicate value.
<? Php $ arr = array (); $ count1 = 0; $ count = 0; $ return = array (); while ($ count <10) {$ return [] = mt_rand (1, 10); $ return = array_flip ($ return); $ count = count ($ return);} // www. bitsCN. comforeach ($ return as $ value) {echo $ value. "";} echo"
"; $ Arr = array_values ($ return); // Obtain the array value foreach ($ arr as $ key) echo $ key." ";?>
Php random number generation function example
<?phpfunction randpw($len=8,$format='ALL'){$is_abc = $is_numer = 0;$password = $tmp =''; switch($format){case 'ALL':$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';break;case 'CHAR':$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';break;case 'NUMBER':$chars='0123456789';break;default :$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';break;} // www.bitsCN.commt_srand((double)microtime()*1000000*getmypid());while(strlen($password)<$len){$tmp =substr($chars,(mt_rand()%strlen($chars)),1);if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){$is_numer = 1;}if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){$is_abc = 1;}$password.= $tmp;}if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){$password = randpw($len,$format);}return $password;}for($i = 0 ; $i < 10; $i++){echo randpw(8,'NUMBER');echo "
";}