To generate unique random numbers within a specified range, consider the following improved methods:
Array with Shuffled Order:
$numbers = range(1, 20); shuffle($numbers);
Wrapped Function:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); return array_slice($numbers, 0, $quantity); }
Example Usage:
$result = UniqueRandomNumbersWithinRange(0, 25, 5);
This will generate and return an array of 5 unique randomly ordered numbers within the range 0-25.
Sample Result:
$result = [14, 16, 17, 20, 1]
The above is the detailed content of How Can I Efficiently Generate Unique Random Numbers Within a Specific Range?. For more information, please follow other related articles on the PHP Chinese website!