Home > Backend Development > PHP Tutorial > How to Generate Unique Random Numbers Within a Specific Range in PHP?

How to Generate Unique Random Numbers Within a Specific Range in PHP?

Susan Sarandon
Release: 2024-12-06 11:17:11
Original
959 people have browsed it

How to Generate Unique Random Numbers Within a Specific Range in PHP?

Generating Unique Random Numbers within a Range

Creating a function to generate unique random numbers within a specified range is a common task in programming. Here's a more optimized alternative to the given code:

function uniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}
Copy after login

This function takes three parameters:

  • $min: The minimum value of the range
  • $max: The maximum value of the range
  • $quantity: The number of unique random numbers to generate

It works by creating an array containing all numbers in the specified range and then shuffling the array. The array_slice() function is then used to extract the specified number of unique random numbers from the shuffled array.

Example:

$numbers = uniqueRandomNumbersWithinRange(1, 20, 5);
print_r($numbers);
Copy after login

This will output an array of 5 unique random numbers within the range of 1 to 20, for example:

Array
(
    [0] => 6
    [1] => 17
    [2] => 14
    [3] => 19
    [4] => 12
)
Copy after login

The above is the detailed content of How to Generate Unique Random Numbers Within a Specific Range in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template