How to generate a random integer from a range [0, N] that is not in a unique integer list with PHP

1 Answer

0 votes
function randomExcluding(int $N, array $excluded): int {
    if (count($excluded) > $N + 1) {
        return -1; // All numbers are excluded
    }

    do {
        $num = random_int(0, $N); // cryptographically secure and inclusive
    } while (in_array($num, $excluded));

    return $num;
}

$excluded = [2, 5, 7];
$N = 14;

echo randomExcluding($N, $excluded) . PHP_EOL;



/*
run:

9

*/

 



answered Nov 19, 2025 by avibootz

Related questions

...