Generating UNIQUE Random Numbers within a range

Generating UNIQUE Random Numbers within a range

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating UNIQUE Random Numbers within a range

The naive approach to generating unique random numbers often involves checking if a newly generated value already exists in an array before adding it. While this logic is sound, the implementation provided in your snippet suffers from two critical issues: performance degradation as the array grows and the use of goto, which disrupts control flow and makes the code difficult to maintain or debug.

When you generate a random number between $min and $max, the probability of a collision increases exponentially as you fill up the available range. If your range is small (e.g., generating 3 numbers between 1 and 5) and you attempt to generate more than half the range, your original algorithm will enter an infinite loop or run for an unacceptably long time because collisions become almost guaranteed on every single iteration.

To solve this efficiently, you should leverage PHP's built-in shuffle() function combined with a sliced array. This technique is known as shuffling and slicing. Instead of generating random numbers one by one and checking for duplicates, you create an array containing all possible integers in your desired range, shuffle that array randomly, and then extract only the number of elements you need.

Here is how to implement this optimized solution:

function getUniqueRandomNumbers(int $count, int $min, int $max): array {
    if ($count > ($max - $min + 1)) {
        throw new InvalidArgumentException("Cannot generate more unique numbers than available in the range.");
    }

    $range = range($min, $max);
    shuffle($range);
    
    return array_slice($range, 0, $count);
}

// Example usage:
// Generates 3 unique numbers between 1 and 15
$numbers = getUniqueRandomNumbers(3, 1, 15);
// Output might be: [9, 2, 14]

This method runs in O(N) time where N is the size of the range, which is significantly faster than your original O(K^2) approach where K is the count of numbers generated. The range() function creates an integer array from $min to $max. The shuffle() function then permutes this array in place using a Fisher-Yates shuffle algorithm, ensuring every permutation has an equal probability. Finally, array_slice() extracts the first N elements.

Handling Edge Cases and Constraints

A crucial trade-off with the shuffling method is memory usage relative to the range size. You must generate an array containing every integer from $min to $max before you can select your subset. If your range is massive (e.g., 1 to 1,000,000) but you only need a handful of numbers, creating that full array consumes unnecessary memory.

In such scenarios where the range is vast but the required count is small, a hybrid approach or a set-based check might be preferable. You would generate random numbers and insert them into a SplSet or a standard PHP associative array to track seen values. This ensures uniqueness without filling a massive initial array, though it reverts to probabilistic performance characteristics similar to your original attempt if the ratio of generated numbers to total range is high.

Laravel Integration

If you are working within a Laravel application, you can wrap this logic into a helper or use Laravel's collection methods for cleaner syntax. Since Laravel 5.4, collections offer powerful utilities that make this pattern concise.

use Illuminate\Support\Collection;

$numbers = (new Collection(range(1, 15)))
    ->shuffle()
    ->take(3)
    ->toArray();

This reads almost like a sentence: "Take the range, shuffle it, take the first three items." While this relies on the overhead of creating a collection object, the performance difference is negligible for typical web application use cases compared to the complexity of managing raw arrays with collision checks.

Why Avoid goto?

Your original code used goto to restart the loop upon finding a duplicate. In modern PHP development, goto statements are almost universally discouraged because they create "spaghetti code," where the control flow jumps arbitrarily through the stack frame. This makes it hard for other developers (or your future self) to understand the execution path at a glance. Refactoring this into a function that throws exceptions or returns early provides a clear linear flow that is easier to test and maintain.

By switching to shuffle() and array_slice(), you eliminate the infinite loop risk entirely, provided you validate that $count does not exceed the available range. This pattern is the industry standard for generating unique random identifiers within bounded sets.

Our network