Home>Article>Backend Development> PHP randomly generates random numbers that are not in a range

PHP randomly generates random numbers that are not in a range

王林
王林 Original
2019-09-19 11:53:59 2626browse

PHP randomly generates random numbers that are not in a range

Idea: Store the generated random numbers in an array, and then remove duplicate values in the array to generate a certain number of non-repeating random numbers.

In PHP website development, sometimes we need to generate a certain number of non-repeating random numbers within a specified range. How to specifically design this function to generate random numbers? We can store randomly generated numbers into an array, but by removing duplicate values while storing them, a certain number of non-repeating random numbers can be generated.

You can also store the values in the specified range into an array, then use shuffle($array) to disrupt the array, and then intercept a certain number of values. But the latter method will generate a larger array when the specified range of random numbers is too large.

The code for the first approach is given below, and the second approach is simpler.

Run results: 48,5,19,36,63,72,82,77,46,16
##Supplementary instructions:

1. When generating random numbers, we used the mt_rand() function. This function generates random numbers several times faster on average than rand().

2. When removing duplicate values from the array, the "flip method" is used, which is to use array_flip() to exchange the key and value of the array twice. This approach is much faster than using array_unique() while removing duplicate values from the array.

3. Before returning the array, first use shuffle() to assign a new key name to the array, ensuring that the key name is a consecutive number from 0-n. If you do not perform this step, it may cause the key names to be discontinuous when deleting duplicate values. If you use for to traverse, there will be problems. However, if you use foreach or do not need to traverse, you do not need shuffle.

Recommended tutorial:

PHP video tutorial

The above is the detailed content of PHP randomly generates random numbers that are not in a range. 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