How can I make an Rand() that always generates only 4 random numbers?

Asked

Viewed 3,280 times

6

How can I make a rand() that at all times generate only 4 random numbers, example: 4562, 9370, 1028...

My code it generates up to 4 numbers, but it comes out 3.

$presenca = rand() % 4000;
  • You always want 4 digits?

  • Yeah, I just want four digits!

3 answers

10


If you want 4 digits then you want 1000 to 9999, as it will generate 0, add 1000 to ensure the minimum 1000 and as it is already adding thousand establish the limit at 9000.

$presenca = rand() % 9000 + 1000;

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

rand(1000, 9999);

I put in the Github for future reference.

Note that if you call the maximum number this way, it is placed as an argument. If using mathematics you always need to put the first number that cannot be generated, that is to say, 10,000 cannot because it has 5 digits, so I used 9000 (apart from the 1,000 initials). this is what the function rand() internally when you receive the range parameters. The rest of 9000 will produce the maximum value of 8999.

  • "as it is already adding thousand establish the limit at 9000", it should not be 8999 then?

  • 1

    @Darleifernandozillmer edited to show the reason.

8

It can generate a number with four digits informing the minimum and maximum arguments in the function call

$presenca = rand(1000, 9999);

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

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

Recommended reading:

Documentation - Rand()

Documentation - str_pad()

5

Can do only by passing the arguments in the function, it is simpler:

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

See more in the documentation:

http://php.net/manual/en/function.rand.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.