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

PHP common method example code for obtaining random numbers

怪我咯
Release: 2023-03-13 14:12:02
Original
1456 people have browsed it

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);
Copy after login

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];
}
Copy after login

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." ";
}
?>
Copy after login

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);
?>
Copy after login

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." ";
?>
Copy after login

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!

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template