How to generate non-repeating random numbers in php

(*-*)浩
Release: 2023-02-25 08:28:01
Original
3979 people have browsed it

How to generate non-repeating random numbers in php

This is nothing to talk about; let’s go straight to the topic and let’s talk about the idea;

The first thing is to use the mt_rand() function to generate a specified number of random numbers;

Then use the array_unique() function to remove duplicates; (Recommended learning: PHP programming from entry to proficiency)

Because of duplicate removal ; so the number obtained is not enough for the specified number;

So, The core is to use a while loop; until the specified number of numbers is obtained;

Go here It can basically be over;

For those who pursue perfection; you can also use sort();

The purpose is not to use for sorting; the main purpose is to format the obtained array key Change;

Let’s talk in code; as follows;

/**
 * 生成不重复的随机数
 * @param  int $start  需要生成的数字开始范围
 * @param  int $end    结束范围
 * @param  int $length 需要生成的随机数个数
 * @return array       生成的随机数
 */
function get_rand_number($start=1,$end=10,$length=4){
    $connt=0;
    $temp=array();
    while($connt<$length){
        $temp[]=mt_rand($start,$end);
        $data=array_unique($temp);
        $connt=count($data);
    }
    sort($data);
    return $data;
}
Copy after login

The above is the detailed content of How to generate non-repeating random numbers in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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!