makeid function - lafnlab/Amore GitHub Wiki
In most software that uses relational databases, the primary key is an auto-incremented number. This means the first entry a table will have primary key of 1, the second entry will have a primary key of 2, and so on. While this isn't bad for most purposes, the numbers can become staggering if a website becomes popular.
For example: Jack Dorsey sent his first tweet in 2006. Three years later, Twitter had reached a billion tweets. Now (late 2018), Twitter gets around a billion tweets every two days.
However, there's no reason that a primary key has to be a number. The purpose of a primary key is to provide a unique reference to a record. Because of that, and because I'm probably subconsciously making things unnecessarily difficult for myself, the function makeid
was born.
The function starts with a string of 189 characters which includes digits, and uppercase and lowercase Latin and Cyrillic letters. The string is split into an array with preg_split
. The array is randomized with PHP's shuffle
function. The randomized array is turned back into a string with join
. The actual id is made when mb_substr
takes the first 10 characters from the string and passes it back to wherever the makeid
function was called.
In theory, this could produce some duplicates, so I always check the database to make sure the id isn't being used before inserting it into the table. For now it works. Here's some stats:
Power | Possibilities | Shorthand |
---|---|---|
189^1 | 189 | less than 200 |
189^2 | 35,721 | 36 thousand |
189^3 | 6,751,269 | 6.8 million |
189^4 | 1,275,989,841 | 1.3 billion |
189^5 | 241,162,079,949 | 241 billion |
189^6 | 45,579,633,110,361 | 45.5 trillion |
189^7 | 8,614,550,657,858,229 | 8.6 quadrillion |
189^8 | 1,628,150,074,335,205,400 | 1.6 quintillion |
189^9 | 307,720,364,049,353,800,000 | 308 quintillion |
189^10 | 58,159,148,805,327,867,842,601 | 58.2 sextillion |