Home >Backend Development >PHP Tutorial >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); }
This function takes three parameters:
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);
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 )
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!