PHP rand() exclude certain numbers

Check if the number is one that you don't want, if it is get a new random number.

function getRandomNumber() {
    do {
        $n = mt_rand(1,1600);
    } while(in_array($n, array(234,1578, 763, 1274)));

    return $n;
}

Always use cryptographically strong algorithms for generating random numbers:

/**
 * @param int   $from     From number
 * @param int   $to       To number
 * @param array $excluded Additionally exclude numbers
 * @return int
 */
function randomNumber($from, $to, array $excluded = [])
{
    $func = function_exists('random_int') ? 'random_int' : 'mt_rand';

    do {
        $number = $func($from, $to);
    } while (in_array($number, $excluded, true));

    return $number;
}

var_dump(randomNumber(1, 100));
var_dump(randomNumber(1, 10, [5, 6, 7, 8]));
var_dump(randomNumber(1, 100, range(10, 90)));

I'd also recommend using the paragonie/random_compat library for compatibility in case of using multiple PHP versions.


Try like this

do {   
    $n = rand(1,1600);

} while(in_array($n, array(234, 1578 ,763 , 1274 ));
echo $n;

<?php

while( in_array( ($n = mt_rand(1,1600)), array(234, 1578 ,763 , 1274) ) );

Tags:

Php