Home >Backend Development >PHP Tutorial >PHP common method example code for obtaining random numbers

PHP common method example code for obtaining random numbers

怪我咯
怪我咯Original
2017-07-11 11:35:071435browse

This article mainly introduces the common methods of simply obtaining random numbers in PHP, and analyzes the simple implementation techniques of PHP to implement random numbers in a specified range and random numbers in a specified character sequence in the form of examples. Friends in need can refer to the following

The example in this article describes the common method of simply obtaining random numbers in PHP. Share it with everyone for your reference, the details are as follows:

1. Directly obtain the number from min-max, such as 1-20:

$randnum = mt_rand(1, 20);

2. In an array Choose one at random (Verification code requires a mixture of letters and numbers)

function randUid(){
 $str = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";//要显示的字符,可自己进行增删
 $list = explode(",", $str);
 $cmax = count($list) - 1;
 $randnum = mt_rand(0, $cmax);
 $uid = $list[$randnum];
}

The following are three ways for PHP to generate random numbers, generating non-repeating numbers between 1-10 Random numbers, examples of php generating non-repeating random numbers

Example 1, using the shuffle function to generate random numbers.

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

Example 2, use the array_unique function to generate random numbers.

<?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 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);// 获得数组的值 
foreach($arr as $key)
echo $key." ";
?>

The above is the detailed content of PHP common method example code for obtaining random numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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