Why does the random code generated by this code store as 7 digits several times instead of 8 digits

The code below generates eight digits, but when stored in db it is sometimes stored as 7 digits. The column width db is taken as int (11) and db is mysql (5.0.45)

srand ((double) microtime( )*1000000); $maxid = rand(0,100000000); $mtidno = str_pad($maxid,8); $shuffled = str_shuffle($mtidno); echo $shuffled; 
+4
source share
2 answers

First, using str_pad , you enter spaces that may fall in the middle of your "random" number.

Modify the str_pad call as follows:

 str_pad($maxid, 8, "0"); 

to get rid of the gaps. However, note that other questions provide better ways to create a random 8-digit number.

Then, when your shuffle result starts at 0 , they will be disabled.

To fix this, you can use CHAR(8) in your database. Then it will show leading zeros.

+5
source

I am surprised that you get even 7 digits. Would padding just add spaces to the right? What happens if the rand function returns 1?

Perhaps you will get 7 and 8 digits just by pure chance - an accident. Try it for a while and you should start to see each combination between 1 and 8 digits.

This is plus what Bart said, lead 0 will just leave.

Speaking of which, if you have rand, why do you shuffle? Should be enough.

 srand ((double) microtime( )*1000000); $maxid = rand(10000000,99999999); echo $maxid; 

Test code (to illustrate the wrong logic)

 srand ((double) microtime( )*1000000); for($i = 0; $i < 1000000; $i++) { $maxid = rand(0,100000000); if($maxid < 100000){ echo $maxid . "<br>"; $mtidno = str_pad($maxid,8); $shuffled = str_shuffle($mtidno); echo $shuffled . "<br>"; } } echo "done <br>"; 

See the following output for clear spaces after shuffling.

 0 0 12207 20 21 7 82397 78 329 64086 64086 42724 4 4 2 27 21362 216 32 57983 7 3 598 
+1
source

Source: https://habr.com/ru/post/1469241/


All Articles