PHP rand() exclude certain numbers

php random number
how to generate unique random number in php
php random 5 digit number
php random string
php random number 6 digits
php random float
laravel random number
how to generate random number without repeat in database using php

I have this:

<?php  $n = rand(1,1600); echo $n ?>

I want to exclude from random numbers let's say 234, 1578 ,763 , 1274 and other numbers. How would I do that?


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

How to randomly generate a number from a range of numbers but , Create a loop that iterates until a generated random number using rand function is not in array. <?php function randomNo($min,$max,$arr) It gets minimum and maximum number and the array of values to exclude. Some time ago I also wanted to become rid of these nasty little while loops. Reduced� The rand() PHP function can also be used to generate a random numberwithin a specific range, such as a number between 10 and 30. If no max limit is specified when using the rand() PHP function, the largest integer that can be returned is determined by the getrandmax() function, which varies by operating system.

Try like this

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

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

Dynamically exclude some numbers from randomly generated , I want to produce some random sequence of numbers between a I am using C for this code and I use random() or randomSeed(seed) and I See who has no social life: :)� If you don't have too many numbers to exclude, it is easier and faster to just retry if you find an unwanted number: $n = 0; while (in_array($n, array(0, 234, 1578 ,763 , 1274))) { $n = rand(1,1600); } echo $n; share. Share a link to this answer. Copy link.

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;

PHP mt_rand() Function, The mt_rand() function generates a random integer using the Mersenne Twister algorithm. PHP 4.2.0: Random number generator is seeded automatically. If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15). Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.

Or avoid making loops with random (possibly infinite) running time:

 * Returns a random integer between $min and $max (inclusive) and
 * excludes integers in $exarr, returns false if no such number
 * exists.
 * $exarr is assumed to be sorted in increasing order and each
 * element should be unique.
function random_exclude($min, $max, $exarr = array()) {

    if ($max - count($exarr) < $min) {
        return false;

    // $pos is the position that the random number will take
    // of all allowed positions
    $pos = rand(0, $max - $min - count($exarr));

    // $num being the random number
    $num = $min;

    // while $pos > 0, step to the next position
    // and decrease if the next position is available
    for ($i = 0; $i < count($exarr); $i += 1) {

        // if $num is on an excluded position, skip it
        if ($num == $exarr[$i]) {
            $num += 1;

        $dif = $exarr[$i] - $num;

        // if the position is after the next excluded number,
        // go to the next excluded number
        if ($pos >= $dif) {
            $num += $dif;

            // -1 because we're now at an excluded position
            $pos -= $dif - 1;
        } else {
            // otherwise, return the free position
            return $num + $pos;

    // return the number plus the open positions we still had to go
    return $num + $pos;

This function chooses a random position and walks the exclusion array to find the free position. It's running time depends on the amount of numbers to exclude. If you want to exclude certain ranges, you may want to adapt the algorithm to take this into account.

Using the PHP Rand() Functions to Generate Random Numbers, However, you can set a specific range to include higher numbers. Rand() Syntax and Examples. The correct syntax for using the rand PHP� Join Date 06-20-2007 Location The Great State of Texas MS-Off Ver 2003, 2010 Posts 40,637

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.

Random Number Excluding Specified Value in Array - PHP, Depends how many values you have in the array compared with the overall range of random numbers. If the number of values is small and the� i want to generate two random numbers in between sequence 1 to 5. like 1 and 3, or 2 and 5, or 1 and 4. but the sequence is subject to one condition. which is like, generate two random numbers from 1 to 5 by excluding one random number. for e.g.

array_rand - Manual, It uses a pseudo random number generator that is not suitable for cryptographic When picking only one entry, array_rand() returns the key for a random entry. For this particular case, i recommend shuffling the array and taking the nth first� between 1 and 4 and 50% of the time gives a number between 6 and 9. This. one's easy though, because it's 50-50. If you want to remove numbers other. than 5, you'd have to modify the proportions. =if ( rand () < 0.5, RANDBETWEEN (1,4), RANDBETWEEN (6,9) ) Let's see.

srand - Manual, Seeds the random number generator with seed or with a random value if no seed is given. Note: There is no need to seed the random number generator with srand () or mt_srand() as this is done automatically. Note: As of PHP 7.1.0, srand() has add the following line to your .htaccess file php_value suhosin.srand.ignore 0 I want to generate random numbers between 2 and 33. But do not want a(i) number. a(i) can be a single number between 2 to 33.

rand - Manual, Note: As of PHP 7.1.0, rand() uses the same random number generator as This means that sequences generated with a specific seed may differ from PHP 7.1� Suppose you need to generate random numbers without duplicates into column A and column B, now select cell E1, and type this formula =RAND(), then press Enterkey, see screenshot: 2. And select the whole column E by pressing Ctrl+ Spacekeys simultaneously, and then press Ctrl+ Dkeys to apply the formula =RAND()to the whole column E.

  • Don't use rand! Use mt_rand, or better random_int if you come from PHP7.
  • Don't use rand, use mt_rand, or better random_int if you come from PHP7.
  • While this one works, using assignment in loop always scares me :|
  • @emix Now it doesn't matter, because rand() is a synonym of mt_rand()
  • You get an extra opcode when using an alias. Still, random_int is much better.
  • it will check whether the generated number is in array or not ,if they are present then again it will goto the do-while loop
  • @ClaudioLudovicoPanetta - why make it recursive, if a while loop works perfectly?
  • Updated my while condition, so that adding new numbers is easier.
  • missing a closing ) on while
  • This is by far the cleanest solution - all the others are either recursive or use loops that can, in theory, be endless and also promote bad programming.