Home >Backend Development >PHP Tutorial >How to Efficiently Generate Unique Random Numbers Within a Specific Range?
Generating Unique Random Numbers within a Range
Question: How can I efficiently generate unique random numbers within a specified range?
Answer:
The provided code generates random numbers within a range but may not guarantee uniqueness. For an optimized solution, consider the following approaches:
1. Array with Random Order:
2. Wrapped Function:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); return array_slice($numbers, 0, $quantity); }
print_r(UniqueRandomNumbersWithinRange(0, 25, 5));
Result:
An array of the specified quantity with unique random numbers within the given range.
The above is the detailed content of How to Efficiently Generate Unique Random Numbers Within a Specific Range?. For more information, please follow other related articles on the PHP Chinese website!