How can I make a rand () that always generates only 4 random numbers?

7

How can I make a rand() that always only generate 4 random numbers, eg: 4562, 9370, 1028 ...

My code it generates up to 4 numbers, but it has 3 times.

$presenca = rand() % 4000;
    
asked by anonymous 26.10.2017 / 15:19

3 answers

10

If you want 4 digits then either 1000 to 9999, as it will generate from 0, add 1000 to guarantee the minimum of 1000 and as you are already adding 1,000, set the limit to 9000.

$presenca = rand() % 9000 + 1000;

There is also a signature that returns the result within the range:

rand(1000, 9999);

Note that if you call this the maximum number is placed as an argument. If you use math, you must always put the first number that can not be generated, that is, 10,000 can not because it has 5 digits, so I used 9000 (taking the initial 1000). this is what the rand() function does internally when it receives the range parameters. The rest of 9000 will produce the maximum value of 8999.

Someone denied the answer maybe because they did not understand it.

    
26.10.2017 / 15:22
9

You can generate a four-digit number by entering the minimum and maximum arguments in the function call

$presenca = rand(1000, 9999);

If you want to display numbers smaller than 1000 use str_pad() to add leading zeros. The first argument is the number, the second the maximum length of the string, the third character (s) to be added and the last argument is where these right character (s) should be added (by default), left or both sides.

$n = rand(1, 9999);
echo str_pad($n, 4, 0, STR_PAD_LEFT);

Recommended reading:

Documentation - rand ()

Documentation - str_pad ()

    
26.10.2017 / 15:23
6

You can do just passing the arguments to the function, it's simpler:

$presenca = rand( int $min , int $max );
$presenca = rand( 1000, 9999 );
  

See more in the documentation:

     

link

    
26.10.2017 / 15:25