Generate Unique Random Numbers in a Range using PHP

range, shuffle & array_slice functions

<?php

function generateRandomNumbers(int $minValue, int $maxValue, int $qty): array
{
    $numbers = range($minValue, $maxValue);
    shuffle($numbers);

    return array_slice($numbers, 0, $qty);
}

$numbers = generateRandomNumbers(1, 10, 4);
print_r($numbers);  // (3, 6, 9, 4)

Leave a Comment

Cancel reply

Your email address will not be published.